Tuples in TypeScript

This entry is part 3 of 4 in the TypeScript series

Tuples in TypeScript

With tuples we can define what type of data (variable type) can be stored in every position ( or few starting positions ) inside of an array. Once you define the tuple you can then use it to declare variables.

Tuple types in TypeScript express an array where the type of certain elements is known. You can enforce types for indexes by enumerating them inside of square brackets

[ type1, type2, type3, type4 ]

The type for elements for which index is larger than the max index defined (index 3 for type4 in previous example) has to be one of the types defined in the brackets (type1, type2, type3, type4).

 

Tuple as a type

You can use tuples to create a new type:

type Tuple = [boolean, number];

let x: Tuple;

x = [false, 0, 3, 3, true];

 

If you prefer to use interfaces you can do the following:

interface ITuple
{
  0: boolean,
  1: number
};

let y: ITuple;
y = [false, 0, 3, 3, true];

 

Dictionary with tuples

In addition, you could create a dictionary type with tuples:

type IDictionary = [string, number];

let myDictionary: IDictionary[];

myDictionary['key1'] = 5;

This is not type safe, since you can store any value in dictionary and compiler will not “complain”:

myDictionary['key2'] = 'some text';



TypeScript Series Navigation: Previous post: << Intersection types in TypeScript
Next post: Decorators with TypeScript >>



Ibrahim Šuta

Software Consultant interested and specialising in ASP.NET Core, C#, JavaScript, Angular, React.js.