Quiz
Warm-up from lesson 1-2: what is the type of let price = 4.99 with no annotation?
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.
Code exercise · typescript
Run the typed array. Then try scores.push("oops") and run again, the compiler will reject it.
Code exercise · typescript
Your turn. Create names: string[] with "Ada", "Grace", "Alan". Push "Linus". Then loop over the array and print each name uppercased with .toUpperCase().