Mapped types and modifiers
type Flags<T> = {
[K in keyof T]: boolean;
};
type Mutable<T> = {
-readonly [K in keyof T]: T[K];
};Build an object type by iterating keys, and add or remove readonly and optionality. Mapping over keyof T preserves those modifiers; mapping over a plain key union does not.
| Type parameter | Description |
|---|---|
T / Keys | The source type, or a key union to iterate. Use keyof T when you want a homomorphic mapping that copies modifiers from T. |
Produces: A new object type. Mapped types exist only at compile time.
Type errors
type error— Omitting a required mapped property is a type error. Assigning to a property that stayed readonly after a homomorphic mapping is a type error.
- Partial, Required, and Readonly are the standard-library versions of adding ?, removing ?, and adding readonly. See that page for those aliases; this page does not repeat those examples.
type Flags<T> = { [K in keyof T]: boolean };
type Options = Flags<{ dark: string; preview: string }>;
const flags: Options = { dark: true, preview: false };
// @ts-expect-error missing preview
const incomplete: Options = { dark: true };
type Source = { readonly a?: string; b: number };
type Homo = { [K in keyof Source]: Source[K] };
type Explicit = { [K in "a" | "b"]: Source[K] };
const homo: Homo = { b: 1 };
// @ts-expect-error a stays readonly in a homomorphic mapping over keyof Source
homo.a = "x";
// @ts-expect-error a is required after mapping over the explicit key union
const missing: Explicit = { b: 1 };
const explicit: Explicit = { a: "x", b: 1 };
explicit.a = "y";
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
const mutable: Mutable<Source> = { b: 1 };
mutable.a = "z";
console.log(flags.dark, explicit.a, mutable.a);Expected output
true y zRelated: Partial, Required, and Readonly, Record