Sub topic 12
keyof with Unions, Intersections, and Optional Properties
This chapter covers how keyof behaves when the type it receives is a union, an intersection, or has optional properties. These cases often give results that look reversed at first. It assumes you know keyof on a plain object type, indexed access types such as T["key"], and basic mapped types. It also assumes you are comfortable reading union and intersection types.
The rule in one sentence
keyof returns the keys you can safely use on every possible value of the type.
- A value of type
A | Bis either anAor aB, so only keys that exist in both are safe. - A value of type
A & Bis both anAand aB, so every key from either one is available.
In set terms, keyof turns a union of types into an intersection of key sets, and an intersection of types into a union of key sets:
| Expression | Equivalent | Meaning | Column |
|---|---|---|---|
| `keyof (A \ | B)` | `keyof A & keyof B` | Keys common to both |
| `keyof (A & B)` | `keyof A \ | keyof B` | Keys from either |
keyof with a union
Start with two object types that overlap in one property.
type Cat = { name: string; meows: boolean };
type Dog = { name: string; barks: boolean };
type PetKey = keyof (Cat | Dog); // "name"
function getPetProp(pet: Cat | Dog, key: PetKey) {
return pet[key];
}
const pet: Cat | Dog = { name: "Tom", meows: true };
console.log(getPetProp(pet, "name")); // Tom
// getPetProp(pet, "meows"); // Error: "meows" is not assignable to "name"The call with "meows" fails even though this particular value has a meows property. The function only knows the parameter is a Cat | Dog, and a Dog has no meows. The compiler rejects the key to protect you from reading a property that may not exist.
The parentheses matter. keyof Cat | Dog parses as (keyof Cat) | Dog, which is a union of a key union and the Dog type. That is almost never what you want.
Discriminated unions
A discriminated union is a union whose members share a literal-typed property, often called kind or type. For these unions, keyof returns the discriminant and any other shared properties.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
type ShapeKey = keyof Shape; // "kind"
type ShapeKind = Shape["kind"]; // "circle" | "square"
// type Radius = Shape["radius"]; // Error: Property 'radius' does not exist on type 'Shape'Indexed access on a union follows the same rule as keyof. You can only index with keys that exist in every member. When you index with a shared key, the result is the union of that property's types across the members.
Getting every key of a union
Sometimes you want all keys that appear in any member. A distributive conditional type does this. A conditional type of the form T extends unknown ? ... : ... is applied to each member of a union separately, and the results are unioned.
type Cat = { name: string; meows: boolean };
type Dog = { name: string; barks: boolean };
type AllKeys<T> = T extends unknown ? keyof T : never;
type PetAllKeys = AllKeys<Cat | Dog>; // "name" | "meows" | "barks"Here keyof Cat is "name" | "meows" and keyof Dog is "name" | "barks". The distribution unions them. This gives you the names, but not safe access. Reading pet["meows"] on a Cat | Dog is still an error. Use this helper to build lookup tables or validators, and narrow the value before you read a non-shared property:
type Cat = { name: string; meows: boolean };
type Dog = { name: string; barks: boolean };
function describe(pet: Cat | Dog): string {
if ("meows" in pet) {
return `${pet.name} meows`;
}
return `${pet.name} barks`;
}
console.log(describe({ name: "Rex", barks: true })); // Rex barkskeyof with an intersection
An intersection merges the members, so the keys merge as well.
type Cat = { name: string; meows: boolean };
type Dog = { name: string; barks: boolean };
type CatDog = Cat & Dog;
type BothKeys = keyof CatDog; // "name" | "meows" | "barks"
const hybrid: CatDog = { name: "Odd", meows: true, barks: true };
const key: BothKeys = "barks";
console.log(hybrid[key]); // trueIntersections are a common way to add fields to an existing type. keyof (Base & Extra) lists the base keys plus the extra ones, with no repetition.
When members disagree on a property type
If both members have the same key with different types, the property type in the intersection is the intersection of those types.
type X = { id: string };
type Y = { id: number };
type XY = X & Y;
type IdType = XY["id"]; // never (string & number)
type XYKey = keyof XY; // "id"keyof XY still lists "id", but the property type is never. Nothing can be assigned to it.
If the clashing property is a literal discriminant, TypeScript goes further and reduces the whole intersection to never. Then keyof gives a surprising answer:
type Impossible = { kind: "a" } & { kind: "b" }; // never
type K = keyof Impossible; // string | number | symbolkeyof never is string | number | symbol, because every key is vacuously valid on a value that cannot exist. If you see this wide key type where you expected a few names, check whether an intersection has collapsed to never.
keyof with optional properties
An optional property is still a key. keyof does not distinguish optional from required keys.
interface Profile {
id: number;
nickname?: string;
readonly createdAt: Date;
}
type ProfileKey = keyof Profile; // "id" | "nickname" | "createdAt"
type Nick = Profile["nickname"]; // string | undefined
type Created = Profile["createdAt"]; // DateTwo details follow from this:
keyofincludes the optional key"nickname". Indexed access on that key addsundefinedto the result, because reading a missing property givesundefined.readonlyhas no effect onkeyofor on indexed access."createdAt"is listed, and the property type is plainDate.
This affects generic code. In a function like getProperty<T, K extends keyof T>(obj: T, key: K): T[K], passing an optional key returns a type that includes undefined. Callers must handle that case.
Optional in one member of a union
A key that is optional in one member and required in the other is still shared, because both members declare it.
type WithNick = { id: number; nickname?: string };
type WithoutNick = { id: number; nickname: string };
type Shared = keyof (WithNick | WithoutNick); // "id" | "nickname"
type NickType = (WithNick | WithoutNick)["nickname"]; // string | undefinedIf one member does not declare the key at all, it is not shared and is dropped from keyof.
Finding required and optional keys
Because keyof treats both kinds alike, you need a helper to separate them. This version uses a mapped type with the -? modifier, which removes optionality. Without it, the lookup at the end would add undefined to the result.
type RequiredKeys<T> = {
[K in keyof T]-?: {} extends Pick<T, K> ? never : K;
}[keyof T];
type OptionalKeys<T> = {
[K in keyof T]-?: {} extends Pick<T, K> ? K : never;
}[keyof T];
interface Profile {
id: number;
nickname?: string;
readonly createdAt: Date;
}
type Req = RequiredKeys<Profile>; // "id" | "createdAt"
type Opt = OptionalKeys<Profile>; // "nickname"
const requiredKey: Req = "id";
const optionalKey: Opt = "nickname";
console.log(requiredKey, optionalKey); // id nicknameThe test works like this. Pick<T, K> keeps just one property. If that property is optional, the picked type accepts an empty object, so {} extends Pick<T, K> is true. If the property is required, an empty object is not assignable and the test is false. Each key maps to either itself or never, and indexing the result with [keyof T] unions the surviving keys.
Optionality survives mapping
A mapped type of the form { [K in keyof T]: ... } copies the ? and readonly modifiers from T. It does this because the mapping is over keyof T directly, which TypeScript treats as a homomorphic mapped type. The built-in Partial<T> and Required<T> use +? and -? to change the modifier on purpose.
type Nullable<T> = {
[K in keyof T]: T[K] | null;
};
interface Profile {
id: number;
nickname?: string;
}
type NullableProfile = Nullable<Profile>;
// { id: number | null; nickname?: string | null | undefined }
const p: NullableProfile = { id: null };
console.log(p); // { id: null }nickname is still optional in the result, so { id: null } is valid. If you map over a separately written key union such as [K in "id" | "nickname"], the modifiers are not copied, and every property becomes required.
Common errors
- Expecting all keys from a union.
keyof (A | B)gives only shared keys. Use theAllKeyshelper for the full list, and narrow before reading. - Missing parentheses. Write
keyof (A | B). Without them you get a union of a key type and a value type. - Treating
keyofas a required-keys check. Optional keys are included. UseRequiredKeyswhen the difference matters. - Forgetting
undefinedafter reading an optional key.T["optionalKey"]includesundefined. Handle it before use. - A surprisingly wide key type. If
keyof Xgivesstring | number | symbolfor a type that is not an index signature, check whetherXhas reduced tonever.
Exercise
Given type A = { id: number; label: string } and type B = { id: number; weight?: number }, what are keyof (A | B) and keyof (A & B)? What is the type of (A | B)["id"]?
Show answer
keyof (A | B) is "id", because it is the only key declared in both members. keyof (A & B) is "id" | "label" | "weight", because an intersection has all keys from both. (A | B)["id"] is number, since id is number in both members.
Exercise
Write a type PickOptional<T> that keeps only the optional properties of T, using OptionalKeys<T> from this chapter. Show its result for { id: number; nickname?: string; bio?: string }.
Show answer
Use Pick with the optional keys:
type PickOptional<T> = Pick<T, OptionalKeys<T>>;
For { id: number; nickname?: string; bio?: string }, OptionalKeys gives "nickname" | "bio", so the result is { nickname?: string; bio?: string }. Pick is a homomorphic mapped type, so the ? modifiers are preserved.