Index Signatures And Record Types

Type dynamic-key objects with index signatures and Record so dictionary-style access stays checked without hard-coding every key.

TypescriptData Integrity

Code

typescriptsnippet
25 lines
// 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);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

99
121
1 hello

How the code works

Index Signatures And Record Types keeps everything in the function withTax.

Applying it

The main signature reads function withTax(region: Region, base: number)

Statements that matter

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

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. The file defines `withTax` at load time.