Sub topic 1
Reading keys and property types with keyof and T[K]
Mapped and conditional types both start from two questions. Which property names does this type have? What type does each property hold? TypeScript answers the first with keyof and the second with indexed access types written T[K]. This chapter covers both operators, how they behave with unions, index signatures, arrays and optional properties, and how to combine them in generic functions.
Prerequisites
This chapter assumes you know the following:
- Basic TypeScript types: object types, unions, and function types.
- Generics: type parameters and constraints such as
T extends object. - Type aliases and interfaces, and the difference between a value and a type.
You do not need to know mapped or conditional types yet. This chapter lays the groundwork for them.
keyof: the keys of a type
The keyof operator takes an object type and produces a union of its property names as string literal types.
type User = { id: number; name: string; email?: string };
type UserKey = keyof User; // "id" | "name" | "email"
const key: UserKey = "name"; // ok
// const bad: UserKey = "age"; // error: Type '"age"' is not assignable to type 'keyof User'Three details matter in practice:
keyofis a type-level operator. It works on types, not on values. To get the keys of a value, first get its type withtypeof.- Optional properties still appear in the key union, because the key exists even when its value may be missing.
- The result is a union of literal types, so you can use it anywhere a union goes: as a parameter type, in a
Record, or later as the thing a mapped type iterates over.
Getting the keys of a value with keyof typeof
The typeof operator in a type position reads the type of a value. Combine it with keyof to get the keys of an object that exists at runtime.
const defaults = { host: "localhost", port: 8080, secure: false };
type DefaultKey = keyof typeof defaults; // "host" | "port" | "secure"
function isDefaultKey(name: string): name is DefaultKey {
return name in defaults;
}
console.log(isDefaultKey("port")); // true
console.log(isDefaultKey("user")); // falseWriting keyof defaults without typeof is an error, because defaults is a value and keyof expects a type.
keyof with unions, intersections and index signatures
The result of keyof changes with the shape of the type you give it.
type A = { id: number; a: string };
type B = { id: number; b: boolean };
type KeysOfUnion = keyof (A | B); // "id"
type KeysOfIntersection = keyof (A & B); // "id" | "a" | "b"
type StringDict = { [key: string]: boolean };
type NumberDict = { [index: number]: string };
type StringDictKey = keyof StringDict; // string | number
type NumberDictKey = keyof NumberDict; // numberA value of type A | B is guaranteed to have only the properties both members share, so keyof of a union is the intersection of the key sets. A value of type A & B has every property from both, so keyof of an intersection is the union of the key sets.
A string index signature gives string | number, not just string. JavaScript converts numeric keys to strings, so dict[0] is legal on a string-indexed object, and TypeScript models that.
Indexed access types: T[K]
An indexed access type looks up the type of a property. It uses the same bracket syntax as a runtime property access, but it runs on types.
type User = { id: number; name: string; email?: string };
type IdType = User["id"]; // number
type NameType = User["name"]; // string
type EmailType = User["email"]; // string | undefinedThe index must be a type, so you write a string literal type in the brackets. If you try to use a variable, you get an error:
const field = "name";
// type Wrong = User[field]; // error: 'field' refers to a value, but is being used as a type
type Right = User[typeof field]; // stringIndexing with a union
When the index is a union, TypeScript looks up each member and returns the union of the results.
type User = { id: number; name: string; email?: string };
type IdOrName = User["id" | "name"]; // number | string
type AnyValue = User[keyof User]; // string | number | undefinedThe pattern T[keyof T] means "the type of every property value in T, combined into one union". You will use it often. Later chapters use it to turn an object type into a union of its values.
Nested lookups
You can chain lookups to reach into nested object types.
type Order = {
id: string;
customer: {
name: string;
address: { city: string; zip: string };
};
};
type City = Order["customer"]["address"]["city"]; // string
type Address = Order["customer"]["address"]; // { city: string; zip: string }Arrays and tuples
Arrays have a numeric index, so number is a valid index type and returns the element type. Tuples also accept specific numeric literals.
type Names = string[];
type Name = Names[number]; // string
type Pair = [string, number];
type First = Pair[0]; // string
type Second = Pair[1]; // number
type Either = Pair[number]; // string | numberA common use is turning a runtime array into a union type. Declare the array as const so TypeScript keeps the literal values, then index it with number.
const roles = ["admin", "editor", "viewer"] as const;
type Role = (typeof roles)[number]; // "admin" | "editor" | "viewer"
function hasRole(role: Role): boolean {
return roles.includes(role);
}
console.log(hasRole("admin")); // trueThe array and the type now come from one source. If you add a role to the array, Role updates with it.
Combining the two: generic property access
The most common use of both operators together is a generic function that reads a property and returns exactly the right type. The constraint K extends keyof T limits the key to names that exist on T. The return type T[K] ties the result to the property you asked for.
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Ada", active: true };
const id = getProperty(user, "id"); // number
const name = getProperty(user, "name"); // string
const active = getProperty(user, "active"); // boolean
// getProperty(user, "age"); // error: Argument of type '"age"' is not assignable to parameter of type '"id" | "name" | "active"'
console.log(id, name, active);Without the generic signature, you would have to choose between any and a wide union such as number | string | boolean. Here, K is inferred as the literal "name", and T["name"] resolves to string.
The same idea works for writing. The value must match the type of the property you chose.
function setProperty<T, K extends keyof T>(obj: T, key: K, value: T[K]): void {
obj[key] = value;
}
const settings = { theme: "dark", fontSize: 14 };
setProperty(settings, "fontSize", 16); // ok
// setProperty(settings, "fontSize", "large"); // error: Argument of type 'string' is not assignable to parameter of type 'number'
// setProperty(settings, "color", "red"); // error: '"color"' is not assignable to '"theme" | "fontSize"'
console.log(settings.fontSize); // 16The next diagram shows how TypeScript resolves a call to getProperty.
Edge cases and common errors
Optional properties add undefined
Under strictNullChecks, an optional property's indexed access type includes undefined. This surprises people who use T[keyof T] and expect only the declared types.
type Profile = { name: string; nickname?: string };
type NicknameType = Profile["nickname"]; // string | undefined
type AllValues = Profile[keyof Profile]; // string | undefined
type StrictNickname = Required<Profile>["nickname"]; // stringRequired<Profile> removes the optional modifier, so indexing into it gives string. The next chapters show how that utility works.
Keys can be string, number or symbol
keyof T for a general T is string | number | symbol, because an object type can have keys of any of those kinds. This causes trouble when you put a key in a template literal or pass it to a function that wants a string.
function describeKey<T>(key: keyof T): string {
// return `key: ${key}`; // error: Implicit conversion of a 'symbol' to a 'string' will fail at runtime
return `key: ${String(key)}`;
}
type StringKeysOf<T> = Extract<keyof T, string>;
type AlsoStringKeys<T> = keyof T & string;
type K1 = StringKeysOf<{ a: 1; 2: "x" }>; // "a"
type K2 = AlsoStringKeys<{ a: 1; 2: "x" }>; // "a"
console.log(describeKey<{ a: number }>("a")); // key: aIntersecting with string (keyof T & string) is the shorthand you will see in many codebases. The key-remapping chapter relies on it.
Special inputs
These are the results of keyof on the types that sit at the edges of the type system.
| Type | `keyof` result | Why | Column | Column |
|---|---|---|---|---|
| `{}` | `never` | No known properties. | ||
| `unknown` | `never` | Nothing can be assumed about its properties. | ||
| `any` | `string \ | number \ | symbol` | Any key is allowed. |
| `never` | `string \ | number \ | symbol` | `never` is assignable to every type, so every key is valid. |
| `string` | Keys of the `String` interface, such as `"length"` and `"charAt"`, plus `number` | Primitives borrow their wrapper's members. |
A key typed too widely loses the lookup
If you widen a key to string, you lose the link between the key and the value type.
const user = { id: 1, name: "Ada" };
function loose(obj: typeof user, key: string) {
// return obj[key]; // error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type
return obj[key as keyof typeof user]; // string | number, a cast that hides mistakes
}
console.log(loose(user, "name"));The cast silences the error but allows any string at runtime. Prefer the generic K extends keyof T signature, which makes the compiler reject bad keys instead.
What this sets up
Every later chapter in this tutorial builds on these two operators. A mapped type iterates over keyof T and uses T[K] for each property. A conditional type inspects T[K] to decide what to do. Once you can predict what keyof and T[K] return for objects, unions, arrays and optional properties, those chapters read much more easily.
Exercise
Given const palette = { red: "#f00", green: "#0f0", blue: "#00f" } as const;, write a type ColorName for its keys and a type ColorValue for its values. Then write a function pick with the signature pick<T, K extends keyof T>(obj: T, key: K): T[K] and say what type pick(palette, "green") has.
Show answer
type ColorName = keyof typeof palette; gives "red" | "green" | "blue". type ColorValue = (typeof palette)[keyof typeof palette]; gives "#f00" | "#0f0" | "#00f", because as const keeps the literal values. function pick<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; } works as written. pick(palette, "green") has the type "#0f0". K is inferred as "green", and (typeof palette)["green"] is the literal "#0f0", which is also readonly because of as const.
Exercise
What are keyof (A | B) and keyof (A & B) for type A = { id: number; a: string } and type B = { id: number; b: boolean }? Explain why they differ.
Show answer
keyof (A | B) is "id" and keyof (A & B) is "id" | "a" | "b". A value of type A | B might be an A or a B, so only the shared key id is safe to read. A value of type A & B must satisfy both types at once, so it has all the keys of both.
Exercise
Why does type Nick = Profile["nickname"] produce string | undefined when Profile is { name: string; nickname?: string }, and how can you get plain string?
Show answer
An optional property may be missing, and reading a missing property gives undefined. With strictNullChecks, the indexed access type includes undefined. Index into Required<Profile> instead, as in Required<Profile>["nickname"], or use NonNullable<Profile["nickname"]>.