Typescript类型体操 #8211; Length of Tuple
题目
创建一个通用的Length
,接受一个readonly
的数组,返回这个数组的长度。
例如:
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
English
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
答案
type Length<T extends readonly any[]> = T extends { length: infer U } ? U : never;
在线演示
作者:Laggage
出处:https://www.cnblogs.com/laggage/p/16651686.html
说明:转载请注明来源
你可能想看: