TypeScript, lesson 7
Real data comes in groups: a week of temperatures, a price list, a class register. This lesson covers the collections you will use most and how to write their types.
An array type is written T[] (or Array<T>, which means the same):
An empty array needs an annotation, otherwise TypeScript cannot know what will go into it:
const names: string[] = [];.
Common methods: push/pop (end), includes(x), indexOf(x) (or -1), slice(a, b) (a copy
of part of the array), , and , which builds a new array by applying
to each element. uses the syntax to pass the elements as
separate arguments.
2 exercises to try what you just read.
join(sep)map(fn)fnMath.max(...temps)temps[10] gives undefined at run time, but its type is still number. TypeScript assumes
indexes are valid unless you enable the stricter noUncheckedIndexedAccess option. Check
length or use a loop instead of guessing indexes.
A tuple is an array with a fixed length where each position has its own type:
Tuples are handy for small pairs, such as returning two values from a function. For anything bigger, an object with named properties is clearer.
RecordAn object type lists property names and their types:
When keys are not known in advance but all values share a type, use Record<K, V>:
MapA Map<K, V> is built for lookups by key, and is usually the best choice when keys come from
data:
Note the type of get: number | undefined, because the key might be missing. The type
checker will not let you do maths with it until you rule out undefined:
This is TypeScript protecting you from the classic "undefined is not a number" bug. Looping
over a map gives [key, value] tuples, in the order the keys were first added:
The input is one line of daily temperatures (whole numbers, at least one) separated by spaces.
Print the average with one decimal, then the day numbers (starting at 1) whose temperature is
above the average, separated by spaces. If no day is above average, print none.
Sample input:
Sample output:
The first input line is a number N. The next N lines are a price list: an item and its
price, like bread 2.40. Every remaining line is something in your basket, written
ITEM QUANTITY. Print one line per basket entry as ITEM xQUANTITY = COST (cost with two
decimals) or ITEM: unknown item, then a final line TOTAL = SUM with two decimals (unknown
items add nothing).
Sample input:
Sample output:
Store the price list in a Map<string, number>, and handle the undefined that get can
return.
const temps: number[] = [12, 15, 9];
temps.push(20); // fine
temps.push("hot"); // error: 'string' is not assignable to 'number'
console.log(temps[0], temps.length, temps.at(-1)); // 12 4 20const reading: [string, number] = ["Oslo", -3];
const [city, degrees] = reading; // destructuring: city is string, degrees is numberconst book: { title: string; pages: number } = { title: "Emma", pages: 474 };const stock: Record<string, number> = { apples: 12, pears: 0 };
stock.plums = 7;
console.log(stock["apples"]); // 12const prices = new Map<string, number>();
prices.set("tea", 2.5);
prices.set("cake", 4);
console.log(prices.has("tea"), prices.size); // true 2
const cost = prices.get("coffee"); // type: number | undefinedconst tea = prices.get("tea");
if (tea !== undefined) {
console.log((tea * 2).toFixed(2)); // inside the if, tea is a number
}for (const [item, price] of prices) {
console.log(`${item}: ${price}`);
}12 15 9 20average 14.0
above 2 42
bread 2.40
milk 1.10
milk 3
jam 1milk x3 = 3.30
jam: unknown item
TOTAL = 3.30