跳到主要内容

Length of Tuple

介绍

创建一个Length泛型,这个泛型接受一个只读的元组,返回这个元组的长度。

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

起点

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'.
];
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'.
];
Take the Challenge

解决方案

Spoiler warning // Click to reveal answer
ts
type Length<T extends readonly any[], Acc extends any[] = []> = T extends readonly [infer First, ...infer Rest] ? Length<Rest, [...Acc, First]> : Acc['length'];
ts
type Length<T extends readonly any[], Acc extends any[] = []> = T extends readonly [infer First, ...infer Rest] ? Length<Rest, [...Acc, First]> : Acc['length'];
ts
// 实现2
type Length<T extends readonly any[]> = T['length']
 
ts
// 实现2
type Length<T extends readonly any[]> = T['length']
 
ts
// 实现3
type Length<T extends readonly any[]> = { [K in keyof T]: any}['length']
ts
// 实现3
type Length<T extends readonly any[]> = { [K in keyof T]: any}['length']
Checkout more Solutions