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.
Code
// 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 helloHow 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
JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Webhook HMAC Signature VerifierVerify and generate HMAC-SHA256 webhook signatures for Stripe, GitHub, and raw hex headers locally using Web Crypto and constant-time comparison.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.