Skip to main content

Length of Tuple

introduction#

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

For example

ts
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
ts
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
View on GitHub

start point#

ts
/* _____________ Your Code Here _____________ */
type Length<T extends any> = any;
 
/* _____________ Test Cases _____________ */
const tesla = ['tesla', 'model 3', 'model X', 'model Y'] as const;
const spaceX = [
'FALCON 9',
'FALCON HEAVY',
'DRAGON',
'STARSHIP',
'HUMAN SPACEFLIGHT',
] as const;
 
type cases = [
Expect<Equal<Length<typeof tesla>, 4>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Length<typeof spaceX>, 5>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
];
Try
ts
/* _____________ Your Code Here _____________ */
type Length<T extends any> = any;
 
/* _____________ Test Cases _____________ */
const tesla = ['tesla', 'model 3', 'model X', 'model Y'] as const;
const spaceX = [
'FALCON 9',
'FALCON HEAVY',
'DRAGON',
'STARSHIP',
'HUMAN SPACEFLIGHT',
] as const;
 
type cases = [
Expect<Equal<Length<typeof tesla>, 4>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Length<typeof spaceX>, 5>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
];
Try
Take the Challenge

my solution#

Spoiler warning // Click to reveal answer
ts
type Length<T extends readonly any[]> = T['length'];
Try
ts
type Length<T extends readonly any[]> = T['length'];
Try
Checkout more Solutions