Sub topic 11
How keyof Treats Index Signatures
An index signature describes an object whose keys are not known ahead of time. This chapter covers what keyof returns for such types, why the result surprises people, and which generic helpers stop working as expected.
It assumes you know keyof, indexed access types (T[K]), and generic constraints like K extends keyof T. It also assumes you can read mapped types.
What an index signature is
An index signature says "any key of this kind maps to this value type." It is the type-level form of a dictionary.
type Dict = { [key: string]: boolean };
const flags: Dict = { dark: true, compact: false };
flags.anything = true; // allowed: any string key is validThe type has no named properties. It has one rule that covers every string key. keyof has to describe all of those keys with a single type, so it returns the key type of the signature instead of a union of literals.
Why keyof on a string signature gives string | number
type Dict = { [key: string]: boolean };
type DictKey = keyof Dict; // string | numberYou wrote string, but keyof returns string | number. At runtime, JavaScript converts every property key to a string, so obj[1] and obj["1"] read the same property. TypeScript follows that rule and allows both forms of access on a string-indexed type.
const flags: Dict = { "1": true };
const a = flags["1"]; // boolean
const b = flags[1]; // boolean, same property at runtimekeyof reports both key types because both are valid. A string index signature accepts number keys too, but a number index signature does not accept arbitrary strings.
Number, symbol, and template literal signatures
The key type of the signature decides the result.
type ByNumber = { [index: number]: string };
type ByNumberKey = keyof ByNumber; // number
type ById = { [id: symbol]: number };
type ByIdKey = keyof ById; // symbol
type DataAttrs = { [key: `data-${string}`]: string };
type DataKey = keyof DataAttrs; // `data-${string}`
const attrs: DataAttrs = { "data-id": "7" };Symbol and template literal signatures need TypeScript 4.4 or later.
| Signature key type | `keyof` result | Accepts access with | Column |
|---|---|---|---|
| `string` | `string \ | number` | any string, any number |
| `number` | `number` | numbers only | |
| `symbol` | `symbol` | symbols only | |
| `` `data-${string}` `` | `` `data-${string}` `` | strings matching the pattern |
Array types follow the same rule. keyof string[] is number plus the names of all array methods such as "length" and "push". The number comes from the array's number index signature.
Mixing known properties with an index signature
A type can have both named properties and an index signature. Every named property must be assignable to the signature's value type.
interface Bad {
[key: string]: string;
count: number; // Error: Property 'count' of type 'number' is not
// assignable to 'string' index type 'string'.
}
interface Headers {
[name: string]: string | number;
"content-length": number;
host: string;
}
type HeaderKey = keyof Headers; // string | numberHeaderKey is not "content-length" | "host" | string | number. Union reduction absorbs the literals "content-length" and "host" into string. The named properties still exist and keep their own types, but keyof no longer lists them.
declare const h: Headers;
const length = h["content-length"]; // number, the named property wins
const other = h["x-custom"]; // string | number, from the signatureThis is the main reason editors lose autocomplete on keys of mixed types. The type system knows "host" is special for lookups, but keyof cannot show it.
Indexed access on index signatures
An indexed access type with the signature's key type returns the signature's value type.
type Dict = { [key: string]: boolean };
type A = Dict[string]; // boolean
type B = Dict[number]; // boolean
type C = Dict["anything"]; // boolean
type D = Dict[keyof Dict]; // booleanDict["anything"] is boolean even though nothing guarantees that key exists. The type system treats the index signature as promising a value for every key.
With noUncheckedIndexedAccess enabled, an expression like flags[key] has type boolean | undefined. The setting changes how expressions are typed. It does not change the type Dict[string], which stays boolean.
function read(flags: Dict, key: string) {
const value = flags[key]; // boolean | undefined under noUncheckedIndexedAccess
return value;
}Turn the setting on for any code that reads from dictionaries. Without it, a missing key is typed as a present value.
Gotcha: K extends keyof T no longer rejects typos
The getProperty helper from earlier chapters rejects unknown keys only when keyof T is a union of literals. With an index signature, keyof T is string | number, so any string passes.
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const loose: Record<string, boolean> = { dark: true, compact: false };
const a = getProperty(loose, "drak"); // compiles, type boolean
const b = getProperty(loose, 42); // compiles, type boolean
console.log(a, b); // undefined undefinedThe call compiles, and the type says boolean, but at runtime the value is undefined. Record<string, boolean> is a mapped type that produces a string index signature, so it behaves like Dict.
The fix is to give the object a type with literal keys. An as const object is the simplest way to do that.
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const strict = { dark: true, compact: false } as const;
const ok = getProperty(strict, "dark"); // type: true
// getProperty(strict, "drak");
// Error: Argument of type '"drak"' is not assignable to
// parameter of type '"dark" | "compact"'.If the key set really is open, keep the index signature but accept that the compiler cannot catch typos. Validate keys at runtime where they enter your program.
Detecting an index signature
You can test whether a type has an open key set. If string is assignable to keyof T, then T has a string index signature.
type HasStringIndex<T> = string extends keyof T ? true : false;
type X = HasStringIndex<{ [key: string]: number }>; // true
type Y = HasStringIndex<{ id: number }>; // false
type Z = HasStringIndex<{ [key: number]: number }>; // falseThe check works because string is assignable to string | number but not to a union of literals or to number. For number signatures, test number extends keyof T. A string signature also makes that second test true, because its keyof includes number.
Extracting the known keys
Sometimes you want the named properties of a mixed type and nothing else. A mapped type with a key-remapping as clause (TypeScript 4.1 and later) can drop the signature keys.
type KnownKeys<T> = {
[K in keyof T as string extends K
? never
: number extends K
? never
: symbol extends K
? never
: K]: T[K];
};
interface Mixed {
[key: string]: unknown;
id: number;
name: string;
}
type Known = KnownKeys<Mixed>; // { id: number; name: string }
type KnownNames = keyof Known; // "id" | "name"When the mapped type iterates over keyof Mixed, it visits each named property and each index signature separately. The as clause maps a wide key like string to never, which removes it, and leaves literal keys unchanged.
Mapped types preserve index signatures
A mapped type of the form [K in keyof T] is homomorphic, meaning it maps over an existing type's keys. It keeps index signatures, optional modifiers, and readonly modifiers.
type Nullable<T> = {
[K in keyof T]: T[K] | null;
};
type Dict = { [key: string]: boolean };
type NullableDict = Nullable<Dict>; // { [x: string]: boolean | null }The result is still a dictionary, not an object with the literal keys string and number. This is usually what you want. It only becomes a surprise if you expected the mapped type to flatten the signature into properties, and it cannot, because the key set is unbounded.
Summary of edge cases
keyofof astringindex signature isstring | number, because numeric keys are converted to strings at runtime.keyofof anumber,symbol, or template literal signature is that same key type.- Named properties alongside a signature are absorbed by
keyofbut keep their own types for lookups. T[K]on a signature returns the value type for any key, even keys that do not exist.noUncheckedIndexedAccessaddsundefinedto expressions such asobj[key], not to the typeT[string].- Homomorphic mapped types keep index signatures.
Exercise
Given interface Scores { [player: string]: number; total: number }, what are keyof Scores and Scores["total"]? Does getProperty(scores, "totl"), using the generic getProperty from this chapter, compile for a value scores: Scores?
Show answer
keyof Scores is string | number. The literal "total" is absorbed by string. Scores["total"] is number, because the named property is looked up directly (and number satisfies the signature's value type). getProperty(scores, "totl") compiles, because "totl" is assignable to string. It returns type number, and at runtime the value is undefined.
Exercise
Write a type IsOpen<T> that is true when T has a string index signature and false otherwise. Then say what IsOpen<Record<"a" | "b", number>> and IsOpen<Record<string, number>> evaluate to.
Show answer
type IsOpen<T> = string extends keyof T ? true : false;. Record<"a" | "b", number> has the keys "a" | "b", and string is not assignable to that union, so IsOpen is false. Record<string, number> produces a string index signature, so keyof is string | number, and IsOpen is true.