DAY 3 OF 30
Arrays and tuples
Yesterday, in one sentence
TypeScript working out the type from the assigned value, instead of you annotating it.
Did you say:
- ✓TypeScript works out the type from the value
- ✓no annotation written
Interview question
An annotation is you writing the type yourself, with a colon. Inference is TypeScript working it out from the value. Inference is the default and covers most code.
Did you say:
- ✓annotation is written by you
- ✓inference is derived from the value
- ✓inference is the default
You add a type annotationType Annotation to an array by writing a
type followed by []. This is called an array type, and it says that every value
inside the array is of that type.
let scores: number[] = [90, 85, 70];
scores.push(65); // ok
scores.push("high"); // ❌ Type 'string' is not assignable to type 'number'
A tuple is an array with a fixed length, where each position has its own type. You write the types as a list inside square brackets.
let pair: [string, number] = ["age", 41];
pair[0]; // string
pair[1]; // number
pair = [41, "age"]; // ❌ the types are in the wrong positions
Check yourself
Square brackets containing a list of types is a tuple. Square brackets after a type is an array.
An array type says every value in the array is the same type. A tuple has a fixed length with a type for each position.
Did you say:
- ✓array type: every value is the same type
- ✓tuple: fixed length
- ✓tuple: a type for each position