JS Built-ins
TypeScriptbeginner

Interface β€” Index Signature

πŸ“– Usage Example
interface Dict { [key: string]: number }
const d: Dict = { a: 1, b: 2 }
d['c'] = 3

An index signature [key: string]: T allows any string key while enforcing a value type.

Interfaces: Index Signatures

An index signature { [key: string]: string } allows an object to have any string keys, all pointing to the same value type.

Challenge: Implement createDict() returning an empty dictionary { [key: string]: string }.

const d = createDict()
d['hello'] = 'world'
d['hello'] // β†’ 'world'
πŸ’‘ Hints (1)
  • β€’ An empty object literal {} satisfies any index signature.