Typescript索引签名
这是 TypeScript 的索引签名(Index Signature),表示对象可以有任意字符串键,值类型为 unknown。
基本含义
interface EventData {
[key: string]: unknown; // 任意字符串 key,值可以是任何类型
type: EventType; // 已知的具体字段
}
相当于告诉 TypeScript:除了声明的已知字段,这个对象还允许有任意其他字段。
实际效果
const event: EventData = {
type: EventType.MESSAGE, // ✅ 已声明字段
customField: "hello", // ✅ 任意额外字段也允许
anything: 123, // ✅
};
没有索引签名时:
interface EventData {
type: EventType;
}
const event: EventData = {
type: EventType.MESSAGE,
customField: "hello", // ❌ 报错:不存在该属性
};
与 Record<string, unknown> 的区别
// 纯索引签名,没有具体字段
type Obj = Record<string, unknown>;
// 等价于
type Obj = { [key: string]: unknown };
// 有具体字段 + 索引签名
interface EventData {
[key: string]: unknown;
type: EventType; // 具体字段必须兼容索引签名的值类型
} // EventType 是 unknown 的子类型,✅ 兼容
注意
具体字段的类型必须能赋给索引签名的值类型,否则报错:
interface Bad {
[key: string]: string; // 所有值必须是 string
count: number; // ❌ number 不能赋给 string
}
interface Good {
[key: string]: unknown; // unknown 兼容所有类型
count: number; // ✅ number 是 unknown 的子类型
}
