获取数组长度
获取数组长度
用例
type arr1 = ["a","1","3"];
type len= Length<arr1 >
//预期:3
实现
type Length<T extends readonly any[]> =T['length']
知识点
- 元组或数组的 length 属性是数字字面量类型,元组或数组的长度, 获取数组每个元素字面类型可以用T[numbrer]
2 只读数组或元组
readonly any[]
- 表示是只读数组,不关心具体的内容
3 readonly any[] 和 [] as const 区别
- readonly any[]: 通常用于泛型约束或函数参数类型,表示“只要是只读数组即可,不关心具体长度和内容”。
T extends readonly any[]
- [] as const: 通常用于定义固定数据,需要 TypeScript 推导出最精确的元组长度和字面量值,常用于枚举映射、路由配置等场景。
const ROUTES = ['home', 'profile'] as const;
// 类型推断为 readonly ["home", "profile"],而不是 string[]

浙公网安备 33010602011771号