Lesson 1-2 introduced inference, and one of its examples is worth recalling before arrays arrive.
The declaration let price = 4.99 with no annotation gets the type number, inferred from its initializer. TypeScript has a single number type covering integers and decimals alike, with no separate float or int type to choose between.
Omitting annotations on initialized variables is normal, idiomatic style. The annotations become valuable exactly where inference runs out, and the first big example of that is the shape of the data inside a collection.
An array of exactly one thing
In the JavaScript courses your arrays could hold anything: [1, "two", true]. Convenient, until a .toUpperCase() meets a number. TypeScript arrays declare their element type:
const scores: number[] = [88, 92, 79]; const names: string[] = ["Ada", "Grace"];
Read number[] as "array of numbers". Now the compiler guards every entry point:
scores.push("95")is an error, only numbers get inscores[0].toUpperCase()is an error, elements are numbers- Inside
for (const s of scores), the loop variablesis already known to be anumber
Inference works here too: const scores = [88, 92] is inferred as number[] automatically.
Working with a number[]
const scores: number[] = [88, 92, 79]; scores.push(95); let total = 0; for (const s of scores) { total += s; } console.log("count: " + scores.length); console.log("total: " + total);
Output
count: 4 total: 354
Everything after the annotation is the same for...of loop you used in the JavaScript course. The type adds no syntax to the loop and no work at runtime.
What it does add is a guarantee at both ends. scores.push("oops") is rejected, so no string can sneak into the array, and because of that the compiler knows s is a number inside the loop. The expression total += s is therefore real arithmetic, not the accidental string concatenation that a single stray "95" would have caused in plain JavaScript.
Uppercasing a string[]
Here is the same idea with strings: an annotated array, one push, then a loop that calls a string method on every element.
const names: string[] = ["Ada", "Grace", "Alan"]; names.push("Linus"); for (const n of names) { console.log(n.toUpperCase()); }
Output
ADA GRACE ALAN LINUS
Reading the code
- The annotation is
string[]because every element is a string. The brackets mean "array of", so the element type always comes first. - Because
nis known to be a string,.toUpperCase()both type-checks and autocompletes in an editor. On anumber[]the same call would be an error, caught before the program ever ran. push("Linus")is accepted since the argument matches the element type. Pushing4instead would fail, which is what keeps the loop's assumption aboutntrue for the array's whole lifetime.