by Timur Dautov

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'];
  • T extends readonly any[]: This ensures T is an array (or tuple) and works even with readonly tuples.
  • T['length']: This accesses the built-in length property of the tuple T

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#