示例工程 04-object-types-structural
04-object-types-structural/03-index-signature/src/main.ts
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
// 演示:索引签名允许任意键;noPropertyAccessFromIndexSignature 要求用方括号访问
export interface Env {
[key: string]: string | undefined;
}
export function read(env: Env, key: string): string {
return env[key] ?? '(unset)';
}
export function keys(env: Env): string[] {
return Object.keys(env).sort();
}
export function run(log: (msg: string) => void = console.log): string[] {
const env: Env = { PATH: '/usr/bin', HOME: '/home/ada' };
const lines = [read(env, 'PATH'), read(env, 'MISSING'), keys(env).join(',')];
for (const line of lines) {
log(line);
}
return lines;
}