18 获取元素长度
约 167 字小于 1 分钟
2025-07-07
题目
创建一个Length
泛型,这个泛型接受一个只读的元组,返回这个元组的长度。
例如:
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
解法
在14 第一个元素 中我们提到了可以用T['length']
取得数组长度:
type Length<T> = T['length']
但是这样会报错Type '"length"' cannot be used to index type 'T'.(2536)
,这是因为我们没有规定T
的类型为数组,加以限制即可。
type Length<T extends readonly any[]> = T['length']