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.
Code
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: 6How 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.