beraliv

Infer tuple length in TypeScript

Example of Length use
Example of Length use

Fifth challenge is Length of Tuple

As for First of Array, we can use it for both arrays and tuples, but for tuples you get exact value.

Extracting length

When we distinguished arrays from tuples in Making object out of tuple, we have seen that we can call ['length'] in types which is really convenient. Let's try this:

Solution
Solution

As usual, for calling tuple methods in types, we need Generic Constrains

For that we used extends readonly any[] constrain.

If we try extends any[] instead, we would get an error for typeof tesla:

The type 'readonly ["tesla", "model 3", "model X", "model Y"]' is 'readonly' and cannot be assigned to the mutable type 'any[]'

It explains itself: we should expect accepting readonly types.

Nice 💫

To try it out, please have a look at the Playground with tests cases

typescript
Alexey Berezin profile image

Written by Alexey Berezin who loves London 🏴󠁧󠁢󠁥󠁮󠁧󠁿, players ⏯ and TypeScript 🦺 Follow me on Twitter