Sub topic 12
`keyof` with Unions, Intersections, and Optional Properties
This chapter assumes that you know TypeScript interfaces, type aliases, union types, JavaScript objects, and basic generics. You should also know that strictNullChecks affects whether undefined appears in a type.
The keyof operator produces a union of valid property keys. For a simple object type, the result is usually easy to predict:
type User = {
id: number;
name: string;
};
type UserKey = keyof User; // "id" | "name"With unions, intersections, index signatures, and optional properties, the result follows TypeScript's rules for safe property access.
`keyof` with unions
Consider two object types:
type Admin = {
id: number;
permissions: string[];
};
type Guest = {
id: number;
expiresAt: Date;
};
type CommonKey = keyof (Admin | Guest); // "id"A value of type Admin | Guest might be either an Admin or a Guest. Code can safely access only properties that both types provide. Therefore, keyof (Admin | Guest) contains the shared keys.
function readId(account: Admin | Guest): number {
return account.id;
}
// This is not safe without narrowing:
// account.permissionsThe keyof result describes what is guaranteed before you check which union member you have.
You can narrow the value first with a property check:
function describe(account: Admin | Guest): string {
if ("permissions" in account) {
return `Admin with ${account.permissions.length} permissions`;
}
return `Guest expires on ${account.expiresAt.toISOString()}`;
}`keyof` with intersections
An intersection type combines requirements from multiple types. A value of type Admin & Guest must have all properties from both types.
type CombinedAccount = Admin & Guest;
type CombinedKey = keyof CombinedAccount;
// "id" | "permissions" | "expiresAt"This is the opposite pattern from a union. An intersection exposes the combined set of keys.
The following table summarizes the difference:
| Type expression | Keys included | Reason | Column | Column |
|---|---|---|---|---|
| `keyof (Admin \ | Guest)` | `"id"` | Safe for either value | |
| `keyof (Admin & Guest)` | `"id" \ | "permissions" \ | "expiresAt"` | Required by the combined value |
Parentheses matter. keyof Admin | Guest means (keyof Admin) | Guest, which is a different and usually unintended type.
Optional properties and indexed access
An optional property may be absent at runtime. With strictNullChecks enabled, indexed access includes undefined:
interface Profile {
name: string;
nickname?: string;
}
type ProfileKey = keyof Profile; // "name" | "nickname"
type Nickname = Profile["nickname"]; // string | undefinedThe key itself is still part of keyof Profile. The optional marker changes the property's value type, not the set of property names.
This distinction matters in generic code:
function getNickname(profile: Profile): string {
return profile.nickname ?? "(none)";
}The ?? operator supplies a fallback when the property is undefined.
When exactOptionalPropertyTypes is enabled, TypeScript also distinguishes an absent property from a property explicitly assigned undefined during assignment checking. However, reading an optional property still commonly requires handling undefined.
Combining union keys with indexed access
For a type with a union of keys, indexed access produces the corresponding union of property types:
type Settings = {
theme: "light" | "dark";
retries: number;
debug?: boolean;
};
type SettingKey = keyof Settings;
// "theme" | "retries" | "debug"
type SettingValue = Settings[SettingKey];
// "light" | "dark" | number | boolean | undefinedSettings[SettingKey] means “the type of any property selected by a valid SettingKey.” Optional properties contribute undefined.
A union type can also contain keys that are not shared. To use such a key, narrow the value first or use a generic type that represents one known member.
Exercise
What are the types of keyof (A | B) and keyof (A & B) when A has keys "x" and "shared", and B has keys "y" and "shared"?
Show answer
keyof (A | B) is "shared", while keyof (A & B) is "x" | "y" | "shared".