Sub topic 11
How utility types are built: mapped types
This chapter assumes you know basic TypeScript syntax (interfaces, type aliases), union and string literal types, and generic syntax such as Array<T>. You should also have met Partial, Pick, Omit and Record in earlier chapters. Here you will see that each of them is a short mapped type, and you will learn the pieces needed to read and write one.
The two building blocks
A mapped type creates a new object type by looping over a set of keys. Two features make that possible:
keyof Tproduces a union of the property names ofT.- An indexed access type
T[K]gives the type of propertyKinT.
interface User {
id: number;
name: string;
email?: string;
}
type UserKeys = keyof User; // "id" | "name" | "email"
type IdType = User["id"]; // number
type NameOrId = User["name" | "id"]; // string | number
type EmailType = User["email"]; // string | undefinedNote that the optional property email gives string | undefined when you read it through an indexed access type.
A mapped type combines both. The syntax is { [K in Keys]: ValueType }. Read it as "for each key K in Keys, make a property named K whose type is ValueType".
interface User {
id: number;
name: string;
email?: string;
}
type Copy<T> = { [K in keyof T]: T[K] };
type UserCopy = Copy<User>;
// { id: number; name: string; email?: string }Copy<User> is structurally identical to User. The optional marker on email carries over. This is a property of the form [K in keyof T]: TypeScript treats it as a homomorphic mapped type and preserves the modifiers (? and readonly) of the original properties. That preservation is the reason the built-in types below are so short.
Modifiers: adding and removing
A mapped type can add or remove two modifiers:
| Syntax | Effect |
|---|---|
| `?` or `+?` | Make the property optional |
| `-?` | Make the property required |
| `readonly` or `+readonly` | Make the property read-only |
| `-readonly` | Remove read-only |
Place the modifier before the colon for ? and before the key for readonly.
Rebuilding the built-in utility types
Each of the built-ins is a one-line mapped type. The versions below carry a My prefix so they do not clash with the real ones.
type MyPartial<T> = { [K in keyof T]?: T[K] };
type MyRequired<T> = { [K in keyof T]-?: T[K] };
type MyReadonly<T> = { readonly [K in keyof T]: T[K] };
type MyPick<T, K extends keyof T> = { [P in K]: T[P] };
type MyRecord<K extends keyof any, V> = { [P in K]: V };
type MyOmit<T, K extends keyof any> = MyPick<T, Exclude<keyof T, K>>;Here is what each one does:
MyPartialloops over every key and adds?. The value type staysT[K].MyRequiredadds-?, which strips the optional marker. For theemailproperty above, the result isstring, because removing?also removes theundefinedthat optionality added.MyReadonlyaddsreadonlyto every property.MyPickloops over a smaller set of keys,K, instead ofkeyof T. The constraintK extends keyof Tguarantees that every key you ask for exists inT.MyRecordhas no input object at all. It loops over the keys you give it and assigns the same value type to each one. The constraintkeyof anymeansstring | number | symbol, the set of valid property keys.MyOmitis built from other utilities. It usesExcludeto remove the unwanted keys fromkeyof T, then hands the remainder toMyPick.
You can verify the equivalence in code. The assignments below compile only if the types match.
interface User {
id: number;
name: string;
email?: string;
}
type MyPartial<T> = { [K in keyof T]?: T[K] };
type MyRequired<T> = { [K in keyof T]-?: T[K] };
const a: MyPartial<User> = {};
const b: MyRequired<User> = { id: 1, name: "Ada", email: "[email protected]" };
// const c: MyRequired<User> = { id: 1, name: "Ada" };
// Error: Property 'email' is missing in type ... but required in type 'MyRequired<User>'.
console.log(a, b);Why `Pick` loops over `K` but `Partial` loops over `keyof T`
The form of the in clause decides whether modifiers are preserved.
- In
[K in keyof T], TypeScript knows the keys come fromT, so it copies the?andreadonlyflags of each original property. - In
[P in K]whereK extends keyof T, TypeScript still recognizes the connection, becauseKis constrained tokeyof T. That is why the realPick<User, "email">keepsemailoptional. - In
Record<K, V>, there is no source type, so there are no modifiers to copy. Every property is required and writable.
interface User {
id: number;
name: string;
email?: string;
}
type EmailOnly = Pick<User, "email">; // { email?: string }
type EmailRecord = Record<"email", string | undefined>; // { email: string | undefined }
const x: EmailOnly = {}; // allowed: email is still optional
// const y: EmailRecord = {}; // Error: Property 'email' is missingRemapping keys with `as`
Since TypeScript 4.1 you can rename or filter keys inside a mapped type with an as clause. The expression after as is evaluated for each key. The result becomes the new key. If it is never, the key is dropped.
interface User {
id: number;
name: string;
email: string;
}
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type UserGetters = Getters<User>;
// { getId: () => number; getName: () => string; getEmail: () => string }
type OnlyStrings<T> = {
[K in keyof T as T[K] extends string ? K : never]: T[K];
};
type StringProps = OnlyStrings<User>;
// { name: string; email: string }string & K narrows the key to its string members, which Capitalize requires, because keys of an object type can also be numbers or symbols.
MyOmit could also be written with as, filtering keys directly. Both forms give the same result for plain object types:
type OmitViaAs<T, K extends keyof any> = {
[P in keyof T as P extends K ? never : P]: T[P];
};This version keeps the modifiers because it still iterates over keyof T.
Writing your own utilities
Once you can read a mapped type, you can write ones the standard library does not include. Two common examples follow.
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type Nullable<T> = { [K in keyof T]: T[K] | null };
interface Config {
readonly host: string;
readonly port: number;
}
type EditableConfig = Mutable<Config>;
const cfg: EditableConfig = { host: "localhost", port: 8080 };
cfg.port = 9090; // allowed, because readonly was removed
type NullableConfig = Nullable<Config>;
const empty: NullableConfig = { host: null, port: null };
console.log(cfg, empty);For nested objects, a mapped type can call itself. DeepPartial applies ? at every level.
type DeepPartial<T> = T extends object
? { [K in keyof T]?: DeepPartial<T[K]> }
: T;
interface Settings {
theme: { color: string; size: number };
}
const ok: DeepPartial<Settings> = { theme: { color: "red" } };
console.log(ok);The conditional T extends object is the stopping condition. Primitive values such as string fall into the : T branch and are returned unchanged.
Common errors and edge cases
- Forgetting the constraint. Writing
type BadPick<T, K> = { [P in K]: T[P] }fails with "Type 'P' cannot be used to index type 'T'". AddK extends keyof T. - Mapping over
keyof anyfor the keys. A mapped type overstringproduces an index signature,{ [x: string]: V }, not a fixed set of properties. Use a union of literals when you want exact keys. - Arrays and functions inside
DeepPartial. Functions and arrays also extendobject. A function property would be turned into an object type with no call signature, and arrays are mapped as arrays of partial elements. Add extra branches (for exampleT extends (...args: any[]) => any ? T : ...) if your data includes functions. - Optional keys and
asremapping. When you remap keys withas, TypeScript may no longer treat the mapping as homomorphic in every case. Check the result with a hover in your editor, or with an assignment test like the ones above. - Index signatures.
keyofon a type with[key: string]: Vgivesstring | number. Mapped types over such a type keep the index signature and lose the literal keys you may have expected.
Summary of the mechanism
A utility type is a generic type alias whose body is a mapped type, a conditional type, or a combination. The mapped part walks over keys. The modifiers ?, -?, readonly and -readonly change the flags. The as clause renames or drops keys. With those four tools you can rebuild every object-shaping built-in and design your own.
Exercise
Write a generic type PickByValue<T, V> that keeps only the properties of T whose value type extends V. For interface Item { id: number; label: string; tag: string }, PickByValue<Item, string> should be { label: string; tag: string }. Which mapped type feature do you need?
Show answer
Use key remapping with as and a conditional that returns never for keys to drop:
type PickByValue<T, V> = {
[K in keyof T as T[K] extends V ? K : never]: T[K];
};
The as clause evaluates T[K] extends V for each key. When it is true, the key is kept. When it is false, the key becomes never and the property disappears from the result.
Exercise
What is the difference between { [K in keyof T]-?: T[K] } applied to { email?: string } and Record<"email", string>? Why does the first one produce { email: string } and not { email: string | undefined }?
Show answer
Both produce { email: string } in this case, but they get there differently. The first is homomorphic and copies the property from T, then -? removes the optional flag, and TypeScript also removes the undefined that optionality added to the type. Record has no source type, so it simply gives each listed key the value type you supplied.