Index Signatures with Known Properties
You'll learn: How to combine specific, named properties with index signatures in the same object type, and why TypeScript enforces strict compatibility rules when you do.
The Core Idea
So far, you've learned that index signatures let you define "catch-all" property types for objects with dynamic keys. But what if you want some properties to be explicit and known, while still allowing extra dynamic properties?
TypeScript lets you combine both in a single object type, but with an important restriction: all known properties must be compatible with (assignable to) the index signature's type.
Why This Rule Exists
Think of the index signature as a promise: "Any property on this object will be of type X." If you declare a specific property with a different type that contradicts that promise, TypeScript rejects it:
type Config = {
timeout: number; // Specific, known property
[key: string]: string; // ❌ Error: number not assignable to string
};
This fails because timeout is a number, but the index signature says all properties should be string. You can't have it both ways.
Making It Work
The solution is to make your index signature type broad enough to include all known property types:
type Config = {
timeout: number;
retries: number;
[key: string]: number | string; // ✅ Known properties match this union
};
const config: Config = {
timeout: 3000,
retries: 5,
endpoint: "api.example.com" // Extra dynamic property
};
Now both the known number properties and dynamic string properties are valid.
Key Takeaway: When combining index signatures with explicit properties, every known property type must be assignable to the index signature's value type—ensuring type consistency across all object keys.