← 中文资源

简体中文版本

索引签名与 Record 类型

用 Record 与索引签名给动态键对象定型:固定键集漏键即报错,动态字段与已知键并存受检。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

99
121
1 hello

实现说明

索引签名与 Record 类型可以归结为函数 withTax。

常见问题

运行之前需要装什么吗?

不需要——用到的每个 API 都随语言运行时自带,无需安装。 文件在加载时定义 withTax。

签名一览:function withTax(region: Region, base: number)

核心语句

return Math.round(base * (1 + taxByRegion[region]));

代码示例

// Record:键集与值类型一体声明
type Prices = Record<string, number>;
const prices: Prices = { eur: 99, usd: 109 };
console.log(prices.eur);

// 固定键集的 Record:漏键即编译错误
type Region = 'eu' | 'na' | 'apac';
const taxByRegion: Record<Region, number> = {
  eu: 0.21,
  na: 0.07,
  apac: 0.10,
};

function withTax(region: Region, base: number): number {
  return Math.round(base * (1 + taxByRegion[region]));
}
console.log(withTax('eu', 100));

// 索引签名:动态键 + 已知键并存
interface Payload {
  id: number;
  [field: string]: string | number;
}
const p: Payload = { id: 1, note: 'hello' };
console.log(p.id, p.note);