BeCuriouzLearn something new every day
Index Signatures: Typing Objects Whose Keys You Don't Know Yet
💡 An index signature { [k: string]: T } types objects with arbitrary keys by fixing the key type and the value type, instead of naming each property.
Sometimes you know the shape of the values in an object but not the names of the keys. Think of a phone book: every entry maps some person's name to a number, but you can't list every possible name ahead of time. For that, TypeScript gives you an index signature — a way to say "any key of this type maps to a value of that type."
The syntax lives inside an interface or type alias: { [k: string]: T }. The k is just a placeholder name (call it anything), the part before the colon is the key type, and T is the value type. Recall from earlier cards how a normal property fixes one specific key — here you're instead describing a whole family of keys at once.
interface PhoneBook {
[name: string]: number;
}
const book: PhoneBook = {};
book["Alice"] = 5551234;
book["Bob"] = 5555678; // any string key, number value — OK
// book["Carol"] = "nope" ❌ Type 'string' not assignable to 'number'Two important catches. First, index-signature keys can only be string, number, or symbol (JavaScript object keys are strings or symbols anyway). Second, and easy to trip over: reading a key gives you type T even when that key doesn't exist at runtime. TypeScript trusts your signature, so book["Zelda"] is typed as number but is actually undefined — turn on noUncheckedIndexedAccess to have the type include undefined and force you to check.