Index Signatures Type Dynamic Keys

Index signatures accept any string key: reading an absent glyph yields undefined at runtime, so presence checks with in guard every lookup.

TypescriptConfig Management

Code

typescriptsnippet
21 lines
interface GlyphWidths {
  [glyph: string]: number;
}

const widths: GlyphWidths = { a: 8, m: 14, ' ': 4 };
console.log('known glyph:', widths['m']);

// 任何字符串键都合法:读取不存在的键得到 undefined,而不是编译错误
console.log('missing glyph:', widths['§']);

// in 检查存在性后再读,避免把 undefined 当宽度
if ('a' in widths) {
  console.log('a measured:', widths['a']);
}

// 动态键来自变量时索引签名照样可用
const glyph = 'm';
console.log('dynamic key:', widths[glyph]);

widths['§'] = 6;
console.log('added:', widths['§']);

Output

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

known glyph: 14
missing glyph: undefined
a measured: 8
dynamic key: 14
added: 6

How the snippet works

Top-level bindings glyph hold the demo state — nothing sits inside a function scope.

The top-level object literal pins a, m as plain values — no derivation, no imports behind them.

Using it

The demo output is labeled (known glyph:, missing glyph:, a measured:), so every printed line has a specific operation behind it.

Key statements

const widths: GlyphWidths = { a: 8, m: 14, ' ': 4 };
[glyph: string]: number;
const glyph = 'm';

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. Its state lives in module-level bindings: `glyph`.