Sub topic 4
Mixing Known Properties with an Index Signature
Some objects have a few fixed fields and also accept extra keys. Examples are a config object with required name and retries fields plus arbitrary user settings, or an HTTP header map with a few well-known headers. TypeScript lets you declare both in one type, but it applies a strict rule to the combination. This chapter explains the rule and why it exists. It also covers how to design around it and the unsoundness that remains.
This chapter assumes you know TypeScript interfaces and type aliases, union types, and how to read an object property with dot and bracket notation. You should also know what a basic string index signature looks like, such as { [key: string]: number }.
The rule: every property must fit the index signature
An index signature says that every string key of the object maps to a value of one type. A named property such as retries is also reached by the string key "retries". So its type has to be assignable to the index signature's value type. If it isn't, the declaration contradicts itself.
interface Config {
[key: string]: string | number;
name: string;
retries: number;
}
const config: Config = {
name: "api",
retries: 3,
region: "eu-west-1",
timeout: 30,
};
console.log(config.name, config.retries, config.region);name is string and retries is number. Both are assignable to string | number, so the interface compiles. Now suppose you narrow the index signature to string only:
// interface Broken {
// [key: string]: string;
// retries: number;
// // Error: Property 'retries' of type 'number' is not assignable to 'string' index type 'string'.
// }TypeScript reports the error on the named property, not on the index signature. The message names both types, so you can see which side to change.
Why the rule exists
Bracket access with a string key can reach any property. Consider this function:
interface Config {
[key: string]: string | number;
name: string;
retries: number;
}
function read(c: Config, key: string): string | number {
return c[key];
}
const config: Config = { name: "api", retries: 3 };
console.log(read(config, "retries"));The compiler cannot know that key is "retries" here. The only safe type for c[key] is the index signature's value type. If retries could be a type outside that union, the return type would be wrong. The rule keeps the index signature truthful for every key, including the named ones.
What you read back: known keys stay precise
Widening the index type does not make the named properties vague. TypeScript uses the declared type when the key is a known name, and the index type otherwise.
interface Config {
[key: string]: string | number;
name: string;
retries: number;
}
const config: Config = { name: "api", retries: 3, region: "eu-west-1" };
const name = config.name; // string
const retries = config["retries"]; // number (a literal key resolves to the named property)
const region = config.region; // string | number (falls back to the index signature)
const key: string = "retries";
const dynamic = config[key]; // string | number (a plain string key can't be resolved)
function describe(value: string | number): string {
return typeof value === "number" ? value.toFixed(1) : value.toUpperCase();
}
console.log(describe(region), describe(dynamic), name, retries);Only the unknown keys pay the cost of the union. Each one must be narrowed with typeof or a similar check before you use it in a type-specific way.
Creating values of the mixed type
An object literal for a mixed type must satisfy both parts:
- Every named required property must be present.
- Every extra key must have a value that fits the index signature.
interface Config {
[key: string]: string | number;
name: string;
retries: number;
}
const ok: Config = { name: "api", retries: 3, debug: "yes" };
// const missing: Config = { name: "api" };
// Error: Property 'retries' is missing in type '{ name: string; }' but required in type 'Config'.
// const wrongExtra: Config = { name: "api", retries: 3, debug: true };
// Error: Type 'boolean' is not assignable to type 'string | number'.
console.log(ok);This also removes excess property checking for that type. A misspelled key such as retires: 5 is accepted, because it is just another entry in the dictionary. This is the main trade-off of the pattern. You gain flexibility and lose typo detection on the extra keys.
Choosing the index value type
You have three common options when named properties have different types.
Union of the property types
This is the approach used above: string | number. It is precise, but every unknown-key read needs narrowing.
`unknown`
If the extra keys are truly arbitrary, use unknown. Every type is assignable to unknown, so named properties never conflict with it. Reads of extra keys must be narrowed before use, which is safer than any.
interface Payload {
[key: string]: unknown;
id: number;
label: string;
}
const payload: Payload = { id: 1, label: "first", tags: ["a", "b"] };
const tags = payload["tags"]; // unknown
if (Array.isArray(tags)) {
console.log(tags.length);
}`any`
[key: string]: any also silences the conflict. It does so by turning off checking for every extra key, and values read from it can be used without any check. Prefer unknown unless you are typing legacy code and need a stopgap.
Optional properties need `undefined`
With strictNullChecks on, an optional property retries?: number has the type number | undefined. That type must also fit the index signature, so the signature has to include undefined.
interface Options {
[key: string]: string | number | undefined;
name: string;
retries?: number;
}
const opts: Options = { name: "api" };
console.log(opts.retries ?? 0);Without | undefined in the signature, TypeScript reports that number | undefined is not assignable to the index type.
A remaining hole: writes through a string key
The rule protects reads, but writes through a general string key are still unsound. The index signature allows any value of the union type for any string key, including the named ones.
interface Config {
[key: string]: string | number;
name: string;
retries: number;
}
const config: Config = { name: "api", retries: 3 };
function set(c: Config, key: string, value: string | number): void {
c[key] = value; // compiles
}
set(config, "retries", "many");
console.log(typeof config.retries); // "string", although the type says numberAfter the call, config.retries is a string while its declared type is number. The compiler cannot see that key was "retries". This is a known limit of the design and not a bug in your code. If the invariants on the named fields matter, avoid exposing a general writer, or use the nested design in the next section.
Separating the fixed part from the dictionary part
Many types should not mix the two at all. If the fixed fields have unrelated types, forcing them into one index signature either weakens every type to unknown or invites the unsound write above. A cleaner alternative is to put the dictionary under its own property.
interface Settings {
name: string;
retries: number;
extras: Record<string, string>;
}
const settings: Settings = {
name: "api",
retries: 3,
extras: { region: "eu-west-1", tier: "gold" },
};
settings.extras["owner"] = "ops";
// settings.extras["retries"] = 5; // Error: Type 'number' is not assignable to type 'string'.
console.log(settings.name, settings.extras["region"]);Each part keeps its own precise type. The named fields cannot be overwritten through a string key, and typos in the named fields are still caught. The cost is one extra level of access (settings.extras.region) and, if the data comes from JSON, a different shape.
| Approach | Named fields stay precise | Extra keys are typed | Typos on named fields caught | Write through a string key is safe |
|---|---|---|---|---|
| Index signature with a union value type | Yes | Union, needs narrowing | Yes | No |
| Index signature with `unknown` | Yes | `unknown`, needs narrowing | Yes | No |
| Index signature with `any` | Yes | No checking | Yes | No |
| Nested `extras` dictionary | Yes | Yes | Yes | Yes |
Number signatures next to string signatures
A type can declare both [key: string] and [index: number]. JavaScript converts numeric keys to strings, so the number signature's value type must be assignable to the string signature's value type.
interface Mixed {
[key: string]: string | number;
[index: number]: number;
}
const m: Mixed = { 0: 10, label: "ten" };
console.log(m[0], m["label"]);
// interface Bad {
// [key: string]: string;
// [index: number]: number; // Error: 'number' index type 'number' is not assignable to 'string' index type 'string'.
// }This is the same rule applied between two signatures. Chapter-level details on key types are covered separately.
Common errors
- Reading the error as being about the index signature. The error is reported on the named property. Fix either the property's type or the signature's value type.
- Widening the index type to
anyto silence the error, then losing checks on every extra key. - Forgetting
undefinedin the signature when a property is optional. - Expecting excess property checks. Any key with a compatible value is accepted.
- Assuming
config[key] = valueis checked against the named property types whenkeyis a plainstring.
Exercise
This interface does not compile. Give two different fixes, and say what each one costs. interface User { [key: string]: string; id: number; name: string; }
Show answer
The property id is a number, which is not assignable to the string index type. Fix 1: widen the signature to [key: string]: string | number. Cost: every unknown key now reads as string | number and needs narrowing. Fix 2: move the dictionary into a separate property, for example interface User { id: number; name: string; attributes: Record<string, string> }. Cost: one extra level of property access, but id and name keep their types and cannot be overwritten through a string key.
Exercise
Given interface Config { [key: string]: string | number; name: string; retries: number } and const c: Config = { name: "a", retries: 1 }, what are the types of c.retries, c["timeout"], and c[k] where const k: string = "retries"?
Show answer
c.retries is number, because the name matches a declared property. c["timeout"] is string | number, because no such property is declared and the index signature applies. c[k] is also string | number, because the variable has the type string and the compiler cannot tell which property it names.
Exercise
Why does interface Options { [key: string]: string | number; retries?: number } fail under strictNullChecks, and what is the smallest change that fixes it?
Show answer
An optional property has the type number | undefined, and undefined is not assignable to string | number. Add undefined to the index signature: [key: string]: string | number | undefined.