Want a faster signal before interviews? Take the Interview Ready Check →

DAY 4 OF 30

Union types

Yesterday, in one sentence

What is the difference between an array type and a tuple type in TypeScript?

Interview question

You write let scores = [90, 85] with no annotation. What type does TypeScript give it?

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

Which type allows an array with a union type containing only strings and numbers?
What is a union type in TypeScript?