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 4type spaceXLength = Length<spaceX>; // expected 5
View on GitHubts
type tesla = ['tesla', 'model 3', 'model X', 'model Y'];type spaceX = ['FALCON 9', 'FALCON HEAVY', 'DRAGON', 'STARSHIP', 'HUMAN SPACEFLIGHT'];type teslaLength = Length<tesla>; // expected 4type spaceXLength = Length<spaceX>; // expected 5
起点
ts
/* _____________ Your Code Here _____________ */typeLength <T extends any> = any;/* _____________ Test Cases _____________ */consttesla = ['tesla', 'model 3', 'model X', 'model Y'] asconst ;constspaceX = ['FALCON 9','FALCON HEAVY','DRAGON','STARSHIP','HUMAN SPACEFLIGHT',] asconst ;typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Length <typeoftesla >, 4>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Length <typeofspaceX >, 5>>,];
Take the Challengets
/* _____________ Your Code Here _____________ */typeLength <T extends any> = any;/* _____________ Test Cases _____________ */consttesla = ['tesla', 'model 3', 'model X', 'model Y'] asconst ;constspaceX = ['FALCON 9','FALCON HEAVY','DRAGON','STARSHIP','HUMAN SPACEFLIGHT',] asconst ;typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Length <typeoftesla >, 4>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Length <typeofspaceX >, 5>>,];
解决方案
Spoiler warning // Click to reveal answer
ts
typeLength <T extends readonly any[],Acc extends any[] = []> =T extends readonly [inferFirst , ...inferRest ] ?Length <Rest , [...Acc ,First ]> :Acc ['length'];
ts
typeLength <T extends readonly any[],Acc extends any[] = []> =T extends readonly [inferFirst , ...inferRest ] ?Length <Rest , [...Acc ,First ]> :Acc ['length'];
ts
// 实现2typeLength <T extends readonly any[]> =T ['length']
ts
// 实现2typeLength <T extends readonly any[]> =T ['length']
ts
// 实现3typeLength <T extends readonly any[]> = { [K in keyofT ]: any}['length']
ts
// 实现3typeLength <T extends readonly any[]> = { [K in keyofT ]: any}['length']