Length of Tuple
问题描述
创建一个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
// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'
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>>,
Expect<Equal<Length<typeof spaceX>, 5>>,
// @ts-expect-error
Length<5>,
// @ts-expect-error
Length<'hello world'>
]
// ============= Your Code Here =============
// 答案
type Length<T extends readonly unknown[]> = T['length']
// 提问 为什么以下这种方式不可以通过校验?
// type Length<T> = T extends readonly any[] ? T['length'] : never
前文说过, as const 会将当前元组直接作为类型使用,即 type readTesla=readonly ['tesla', 'model 3', 'model X', 'model Y'],获取元组的长度时,首先要限制当前传入的泛型是一个数组,即继承自数组 T extends readonly unknown[] ,上述的提问中,泛型 T 的范围不确定,没有约束郸泛型 T 的类型,当判断 T extends readonly any[] 这里的 T 必须为数组,所以会报错。