2.10 Tuple types

A tuple type can be used to represent an array that stores variables of multiple types or key value pairs.

Getting Ready

All you need to be able to use types aliases is an installation of TypeScript version 2.0 or higher.

How to do it…

You can declare a tuple type by using a comma separated sequence of types enclosed in square brackets:

let t: [number, string] = [1, 'hello'];

How it works…

The TypeScript compiler is able to identify the type of the elements of each of the items in the array and will effectively prevent an assignment of the wrong type:

t = []; // Error
t = [1];    // Error
t = [2, 'test'];    // OK
t = ['test', 2];    // Error
t = [2, 'test', true];  // Error

There’s more…

The TypeScript language services will also assist us during the development as it is able to detect the type of each of the items in the array:

const x: [number, string] = [1, 'Hello'];
const x0 = x[0];  // Type number
const x1 = x[1];  // Type string
const x2 = x[2];  // Type {}

Source Code

Tuple types


Shiv Kushwaha

Author/Programmer