Mapped types
Overview
Utility types like Partial and Readonly aren’t magic — they’re mapped types, a feature you can use yourself. A mapped type builds a new object type by going through the keys of another type and deciding what each property becomes. It’s like Array.map, but for the properties of a type.
The syntax
type Flags<T> = {
[K in keyof T]: boolean;
};
type User = { name: string; age: number; admin: boolean };
type UserFlags = Flags<User>;
// { name: boolean; age: boolean; admin: boolean }[K in keyof T]loops over every key ofT, calling each oneK.- The part after the colon is the new property type.
Using the original property type: T[K]
Inside the mapping, T[K] is the type of the current property, so you can transform it rather than replace it:
type Nullable<T> = { [K in keyof T]: T[K] | null };
type Getters<T> = { [K in keyof T]: () => T[K] };
type Validators<T> = { [K in keyof T]: (value: T[K]) => string | null };
type UserValidators = Validators<User>;
// {
// name: (value: string) => string | null;
// age: (value: number) => string | null;
// admin: (value: boolean) => string | null;
// }Every validator’s parameter has the exact type of the field it checks — and if someone adds a field to User, every Validators<User> object must add a validator for it.
Modifiers: readonly and ?
You can add or remove readonly and ? on every property. That’s exactly how the built-ins are written:
type MyPartial<T> = { [K in keyof T]?: T[K] }; // add ?
type MyRequired<T> = { [K in keyof T]-?: T[K] }; // remove ?
type MyReadonly<T> = { readonly [K in keyof T]: T[K] }; // add readonly
type Mutable<T> = { -readonly [K in keyof T]: T[K] }; // remove readonly+ is the default (+? means the same as ?). Mapped types over keyof T preserve the original modifiers unless you change them.
Mapping over any union of keys
The thing after in can be any union of string literals, not just keyof T:
type Day = "mon" | "tue" | "wed";
type Schedule = { [D in Day]: string[] };
// { mon: string[]; tue: string[]; wed: string[] }That’s how Record<K, V> is defined: { [P in K]: V }.
Renaming keys with as
Add as after the key to compute a new name. Combined with template literal types (Template literal types), this generates related property names:
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type UserGetters = Getters<User>;
// { getName: () => string; getAge: () => number; getAdmin: () => boolean }string & K keeps only string keys (keys can also be numbers or symbols, which Capitalize can’t handle).
Filtering keys
If as produces never, the key is dropped. With a conditional type (next lesson), you can keep only certain properties:
type OnlyStrings<T> = {
[K in keyof T as T[K] extends string ? K : never]: T[K];
};
type UserText = OnlyStrings<User>; // { name: string }A practical example: form state
type FormState<T> = {
values: T;
touched: { [K in keyof T]?: boolean };
errors: { [K in keyof T]?: string };
};
type SignupForm = FormState<{ email: string; password: string }>;Form libraries such as React Hook Form use mapped types like these, which is why their APIs autocomplete your field names.
Homomorphic mapped types
A mapped type over keyof T is called homomorphic (“same shape”). Besides keeping modifiers, it has one more nice property: applied to an array or tuple type, it maps the elements and keeps it an array:
type Boxed<T> = { [K in keyof T]: { value: T[K] } };
type B = Boxed<[string, number]>; // [{ value: string }, { value: number }]You’ll rarely need that, but it explains why Readonly<string[]> gives readonly string[].
Remember:
[K in Keys]: NewTypebuilds an object type one key at a time. UseT[K]for the original type,?/readonly(with-to remove) for modifiers, andasto rename or filter keys.
Validators and getters from one type
Given type Signup = { email: string; age: number; terms: boolean }, write three mapped types: (1) Validators<T> — for each key, a function (value: T[K]) => string | null; (2) Errors<T> — for each key, an optional string; (3) Getters<T> — for each key k, a method named get + capitalised key (getEmail) returning T[K], using key remapping with as. Then write validate<T>(values: T, validators: Validators<T>): Errors<T> (loop over Object.keys(validators) as (keyof T)[]) and makeGetters(values: Signup): Getters<Signup>. Validate two signups and print the errors, then call getAge() on the getters.
type Signup = { email: string; age: number; terms: boolean };
// 1. Validators<T>
// 2. Errors<T>
// 3. Getters<T>
// validate() and makeGetters()type Signup = { email: string; age: number; terms: boolean };
// 1. Validators<T>
type Validators<T> = { [K in keyof T]: (value: T[K]) => string | null };
// 2. Errors<T>
type Errors<T> = { [K in keyof T]?: string };
// 3. Getters<T>
type Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] };
function validate<T>(values: T, validators: Validators<T>): Errors<T> {
const errors: Errors<T> = {};
for (const key of Object.keys(validators) as (keyof T)[]) {
const message = validators[key](values[key]);
if (message !== null) errors[key] = message;
}
return errors;
}
const signupRules: Validators<Signup> = {
email: (email) => (email.includes("@") ? null : "email looks wrong"),
age: (age) => (age >= 16 ? null : "must be 16 or older"),
terms: (accepted) => (accepted ? null : "please accept the terms"),
};
console.log(validate({ email: "asha@example.com", age: 29, terms: true }, signupRules)); // {}
console.log(validate({ email: "nope", age: 12, terms: false }, signupRules));
function makeGetters(values: Signup): Getters<Signup> {
return {
getEmail: () => values.email,
getAge: () => values.age,
getTerms: () => values.terms,
};
}
const getters = makeGetters({ email: "ben@example.com", age: 34, terms: true });
const age: number = getters.getAge();
console.log(age); // 34Summary
- A mapped type loops over keys:
{ [K in keyof T]: … }creates one property per key of T. - Use
T[K]inside to refer to each property’s original type, and transform it as needed. - Add or remove modifiers with
readonly,-readonly,?and-?— that’s how Partial, Required and Readonly work. asrenames keys (often with template literal types) and can filter them out by mapping tonever.- Mapped types keep related types in sync with a source type: forms, validators, getters, event handlers.