Skip to content

Length of Tuple

For given a tuple, you need create a generic Length, pick the length of the tuple.

Tuple is an array with fixed values, e.g. ['tesla', 'model 3', 'model X', 'model Y'].

For example:

type tesla = ['tesla', 'model 3', 'model X', 'model Y']
type spaceX = ['FALCON 9', 'FALCON HEAVY', 'DRAGON', 'STARSHIP', 'HUMAN SPACEFLIGHT']

type teslaLength = Length<tesla>  // expected 4
type spaceXLength = Length<spaceX> // expected 5

Solution

type Length<T extends readonly any[]> = T['length'];

Example of Usage:

type tesla = ['tesla', 'model 3', 'model X', 'model Y'];
type spaceX = ['FALCON 9', 'FALCON HEAVY', 'DRAGON', 'STARSHIP', 'HUMAN SPACEFLIGHT'];

type teslaLength = Length<tesla>;     // 4
type spaceXLength = Length<spaceX>;   // 5

This solution works because TypeScript can infer the exact length of tuples at compile time, and the length property on a tuple type returns the numeric literal type corresponding to its length.

References