keyof with Index Signatures
What You'll Learn
You'll discover how keyof behaves differently when a type has string or number index signatures, producing string | number instead of specific property names.
The Core Idea
Up until now, you've seen keyof extract literal property names from object types. But what happens when you use it on a type with an index signature—a type that allows arbitrary properties?
When TypeScript encounters a type with:
- A string index signature
[key: string]: T,keyofproducesstring | number - A number index signature
[key: number]: T,keyofproducesnumber
Wait, why string | number for string index signatures? Because in JavaScript, numeric property keys are automatically converted to strings. TypeScript reflects this by allowing both.
The Behavior in Action
type StringIndexed = {
[key: string]: boolean;
};
type Keys1 = keyof StringIndexed;
// Keys1 = string | number
type NumberIndexed = {
[key: number]: string;
};
type Keys2 = keyof NumberIndexed;
// Keys2 = number
Even if you have known properties alongside an index signature, keyof still produces the broader union:
type Mixed = {
name: string;
[key: string]: string | number;
};
type Keys3 = keyof Mixed;
// Keys3 = string | number (not just "name")
This means you can't iterate over "just the known keys" using keyof when an index signature is present—you get the entire possibility space instead.
Why This Matters
This behavior protects you from assuming you know all possible keys. If a type accepts arbitrary string keys, TypeScript tells you: "any string (or number) could be a key here."
Key Takeaway:
When keyof operates on a type with a string index signature, it produces string | number; with a number index signature, it produces number—reflecting the full range of possible keys, not just known properties.