The Index Signature Constraint Rule
What you'll learn: Why TypeScript requires all known properties in an object to be compatible with the index signature's value type.
The Core Problem
When you add an index signature to an object type, TypeScript enforces a strict rule: every explicitly defined property must have a type that's assignable to the index signature's value type.
Think of it like a contract for a filing cabinet. If your cabinet's label says "all folders contain numbers," you can't have one specific labeled drawer that contains strings. Everything must match the general promise.
Why This Rule Exists
type Config = {
maxRetries: number; // ✅ OK: number is assignable to number
[key: string]: number;
};
type BrokenConfig = {
maxRetries: number; // ✅ OK
apiKey: string; // ❌ ERROR!
[key: string]: number;
};
// Error: Property 'apiKey' of type 'string' is not
// assignable to 'string' index type 'number'
The reason? Someone could access apiKey through the index signature (config["apiKey"]), and TypeScript guarantees that returns a number. If apiKey were actually a string, that guarantee would be broken.
Working Within the Constraint
Option 1: Union the index signature type
type FlexibleConfig = {
maxRetries: number;
apiKey: string;
[key: string]: number | string;
};
Option 2: Make the property optional
type MixedConfig = {
apiKey?: string; // Optional properties are exempt
[key: string]: number;
};
Key Takeaway: All known properties must be assignable to your index signature's value type—broaden the signature with unions or make conflicting properties optional to satisfy TypeScript's consistency requirements.