DAY 4 OF 30
Union types
Yesterday, in one sentence
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
Interview question
let scores = [90, 85] with no annotation. What type does TypeScript give it?number[]. Type inference reads the values, sees they are all numbers, and gives
it an array type.
Did you say:
- ✓inference, not annotation
- ✓array type
- ✓number[]
A union type says a value can be one of several types. You add a type annotationType Annotation for one by writing a colon
followed by the types separated by a |.
let id: string | number;
id = "abc"; // ok
id = 41; // ok
id = null; // ❌ Type 'null' is not assignable to type 'string | number'
A union can be used anywhere a type can, including inside an array typeArray Type.
let array: string[] = ["hello", "there"]; // only strings, any length
let tuple: [string, number] = ["hello", 34]; // fixed length and position
let union: (string | number)[] = ["hello", 34]; // strings or numbers, any length
tuple is a fixed length array with only two values inside, a string and a number.
The brackets in union indicate that this is an array type with a union type inside,
so it can contain strings or numbers in any position, and the length is not fixed.
The brackets around a union matter. (string | number)[] is an array of strings or
numbers. Without them, string | number[] means a string, or an array of numbers.
Check yourself
The brackets make the union apply to the whole array. string | number[] is a string or an array of numbers, and [string, number] is a tuple with a fixed length.
A type that says a value can be one of several types, written with | between
them.
Did you say:
- ✓a value can be one of several types
- ✓written with `|` between them