获取元组长度
题目
创建一个通用的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
题目来源:https://tsch.js.org/18/zh-CN
解答
type Length<T extends readonly any[]> = T['length'];
数组的长度,用T['length']
可以推导出来。
这里加readonly
的原因是,如果数组是用const
声明,则必须是readonly
。