索引签名
在 TypeScript 中,索引签名(Index Signature) 是一种用于描述“键值对”结构的类型声明方式,适用于键名不确定但键值类型已知的场景。它允许对象或数组具有动态属性,同时保持类型安全。
对象索引
ts
interface Example {
[key: string]: number
}- [key: string] 表示对象可以有任意数量的 字符串类型 的键。
- key可以是任意名称,表示键:
[props:string]:number - number 表示这些键对应的值必须是 number 类型。
数组索引
数组本质上也是对象,其索引是数字类型,因此可以用数字索引签名来约束:
ts
interface NumberArray {
[index: number]: string
}
const arr: NumberArray = ['a', 'b', 'c'] // 类似数组[number]
[number] 是 TypeScript 中的一种索引访问类型(indexed access type)语法,用来从数组/元组类型中提取元素的类型。
ts
const arr = ['a', 'b', 'c'] as const;
type ArrType = typeof arr; // readonly ["a", "b", "c"]
type ElementType = ArrType[number]; // "a" | "b" | "c"ArrType是一个只读元组类型:readonly ["a", "b", "c"]ArrType[number]的意思是:“这个数组中所有可能的数字索引对应的值的类型”- 所以结果就是:
"a" | "b" | "c"
ts
const obj = { a: 1, b: 2, c: 3 };
type ObjValues = typeof obj[keyof typeof obj]; // 1 | 2 | 3- 对象用
keyof typeof obj拿到所有 key,再用索引访问拿 value - 数组用
number作为索引类型,拿到所有元素的类型
