TypeScript · Lesson 28 of 42
Mapped types: transforming every property
Build new types by looping over keys with [K in keyof T], adjust optional and readonly modifiers, and filter or rename keys with as.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will be able to write the transformations behind the built-in utility types, and your own. A mapped type is a loop over keys that produces a new object type, and once you see how it works, Partial, Readonly and Record stop being magic.
The basic form
A mapped type uses the in keyword to loop over a union of keys. Here, every property becomes a boolean:
type User = { name: string; age: number; admin: boolean };
type Flags<T> = { [K in keyof T]: boolean };
const touched: Flags<User> = { name: true, age: false, admin: false };
console.log(touched);{ name: true, age: false, admin: false }Read { [K in keyof T]: boolean } as: "for every key K in the keys of T, make a property named K of type boolean". K takes each key in turn, like a loop variable. The compiler checks that your value has exactly those keys:
type User = { name: string; age: number };
type Flags<T> = { [K in keyof T]: boolean };
const touched: Flags<User> = { name: true };example.ts(4,7): error TS2741: Property 'age' is missing in type '{ name: true; }' but required in type 'Flags<User>'.Keeping the original types
Often you want the new property to depend on the old one. Use the indexed access type T[K]:
type Nullable<T> = { [K in keyof T]: T[K] | null };
type User = { name: string; age: number };
const draft: Nullable<User> = { name: "Asha", age: null };
console.log(draft);{ name: 'Asha', age: null }Nullable<User> is { name: string | null; age: number | null }. One definition works for every object type.
Rebuilding Partial and Readonly
Here are the built-in utilities written by hand, using the question mark and readonly modifiers:
type MyPartial<T> = { [K in keyof T]?: T[K] };
type MyReadonly<T> = { readonly [K in keyof T]: T[K] };
type Point = { x: number; y: number };
const partial: MyPartial<Point> = { x: 1 };
const frozen: MyReadonly<Point> = { x: 1, y: 2 };
console.log(partial, frozen);{ x: 1 } { x: 1, y: 2 }And Record is a mapped type over an arbitrary key union:
type MyRecord<K extends string, V> = { [P in K]: V };
const scores: MyRecord<"math" | "art", number> = { math: 90, art: 75 };
console.log(scores);{ math: 90, art: 75 }Adding and removing modifiers
You can add a modifier with + (the default) or remove one with -. Removing ? makes properties required, and removing readonly makes them writable:
type Config = { readonly host?: string; readonly port?: number };
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type Complete<T> = { [K in keyof T]-?: T[K] };
const editable: Mutable<Config> = {};
editable.host = "localhost";
const full: Complete<Config> = { host: "localhost", port: 8080 };
console.log(editable, full);{ host: 'localhost' } { host: 'localhost', port: 8080 }Required<T> is exactly { [K in keyof T]-?: T[K] }.
Key remapping with as
A mapped type can rename keys by adding an as clause after the key. If the new key is never, that property is dropped, which gives you filtering:
type User = { id: number; name: string; email: string };
type WithoutId<T> = { [K in keyof T as Exclude<K, "id">]: T[K] };
const input: WithoutId<User> = { name: "Asha", email: "asha@example.com" };
console.log(input);{ name: 'Asha', email: 'asha@example.com' }You can also filter by the type of the value. This keeps only the properties that are strings:
type OnlyStrings<T> = {
[K in keyof T as T[K] extends string ? K : never]: T[K];
};
type Mixed = { id: number; name: string; email: string; active: boolean };
const strings: OnlyStrings<Mixed> = { name: "Asha", email: "asha@example.com" };
console.log(strings);{ name: 'Asha', email: 'asha@example.com' }The T[K] extends string ? K : never part is a conditional type, covered in the next lesson. Read it as "if the value is a string, keep the key; otherwise drop it". The following lesson on template literal types also uses as to build new key names such as getName from name.
Mapped types over unions
A mapped type does not have to start from an object. Looping over any union of string keys works, which is how Record operates. This is handy for building a lookup that must cover every case, like the Role map in the utility types lesson, because adding a member to the union makes the compiler demand a new entry.
Common mistakes
Forgetting [K in keyof T]. A mapped type needs the loop over keys. Without in, you have an index signature, which is a different thing.
Losing the original types. If you want to keep each property's type, write T[K], not a fixed type.
Confusing - with a minus sign on a value. -? and -readonly only mean "remove this modifier".
Making mapped types too clever. If a transformation needs five lines to explain, write a plain interface and be done.
Exercise
Write Optionalise<T, K extends keyof T> that makes only the keys K optional (hint: combine Omit, Pick and Partial, or use a mapped type with as). Write Getters<T> that turns each property type into a function returning it, { name: () => string }. Write OnlyNumbers<T> using key remapping. Test each with an object type of your own.
Next: Conditional types and infer.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.