索引签名描述当您事先不知道属性名称时这些属性的类型——对具有动态键的字典/映射进行建模。
ts
interface StringMap {
[key: string]: number; // any string key maps to a number
}
: = { : , : };
scores. = ;
scores.;
scores.;
索引签名描述当您事先不知道属性名称时这些属性的类型——对具有动态键的字典/映射进行建模。
interface StringMap {
[key: string]: number; // any string key maps to a number
}
: = { : , : };
scores. = ;
scores.;
scores.;
使用简单的索引签名时,编译器假设每个键都存在,所以 scores.typo 被类型化为 number,即使它在运行时实际上是 undefined。启用 noUncheckedIndexedAccess 可以解决这个问题:
// with noUncheckedIndexedAccess: true
scores.math; // number | undefined → forces you to handle the missing case
interface Config {
name: string; // known property
[key: string]: string | number; // plus arbitrary extra keys
}
所有命名属性都必须可分配给索引签名的值类型。
type Scores = Record<string, number>; // same as the index signature
type Roles = Record<"admin" | "user", boolean>; // constrained keys
Record 是习惯性的简写形式,支持受限的键联合,而普通的 [key: string] 不支持。
索引签名对真正动态键控的对象进行建模(查找表、缓存、解析的 JSON 映射)。
了解安全性注意事项 (noUncheckedIndexedAccess) 并更倾向使用 Record<K, V> 以提高可读性——当键真正开放并且您希望真正的迭代/大小语义时,更倾向使用 Map。