TypeScript Basics: Tuples
Welcome to the Tuples lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
TypeScript supports tuples, which are arrays of fixed length. For example,
[number, number]is a tuple of two numbers. It must be exactly two numbers; not one and not three. If the length doesn't match, it's a type error.>
let numbers: [number, number] = [1, 2];numbers[0];Result:
1
>
let numbers: [number, number] = [1];Result:
type error: Type '[number]' is not assignable to type '[number, number]'. Source has 1 element(s) but target requires 2.
In the above error, the compiler is telling us that our tuple had only one element, at index 0. Index 1 was missing.
Tuples can have different types in each index. This is different from arrays, where every element must have the same type.
>
let numberAndString: [number, string] = [1, 'a'];numberAndString[1];Result:
'a'
>
let numberAndString: [number, string] = [1, 2];numberAndString[1];Result:
type error: Type 'number' is not assignable to type 'string'.