Length of A Tuple


Problem - On Github

This time we are looking at retrieving the length of a given tuple as a type.

Out initial type given by the puzzle creator is

type Length<T> = any

Solution

Continuing on with new ways to reference specific properties from a tuple, we now need to find the length property. Previously we have used T[number] for all indexes and T[0] for the first. Turns out we can do the same thing to reference specific properties on our object as well. Lets add in T['length'] to our type.

type Length<T> = T['length']

Now we need to narrow what type T is to make sure it is a valid tuple. First we make sure T is an array by adding extends any[] which would work for any normal array type. The problem is that we are actually passed constant arrays. These are not mutable and therefore do not match the normal array type.

What we need to do is tell Typescript that we expect the arrays to also be readonly. This leaves us with:

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


What to read more? Check out more posts below!