Length of Tuple
Challenge
For given a tuple, you need create a generic Length
, pick the length of the
tuple.
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
We know that we can use property length
to access the length of the array in
JavaScript. We can do the same in types as well:
type Length<T extends any> = T["length"];
But going that way we will get the compilation error Type 'length' cannot be
used to index type 'T'.
. We could try to give a hint to TypeScript and tell that
our input type parameter has the length
property:
type Length<T extends { length: number }> = T["length"];
However, in this case T encompasses both arrays and strings. Instead, check that T is an array with:
type Length<T extends readonly any[]> = T["length"];
Comments