Mapped types iterate over the keys of a type and transform each property. Syntax: type M<T> = { [K in keyof T]: Transform<T[K]> }. The +/- modifier adds or removes ? (optional) and readonly. The as clause (TypeScript 4.1+) remaps key names. Mapped types that take a generic parameter and map over keyof T are homomorphic — they preserve modifiers from the original type. Built-in Partial, Readonly, Required, and Pick are all homomorphic mapped types.
Using as clause to generate getter method types.
All of Partial, Required, Readonly, and Pick are 1-4 line mapped types. Learning to write your own mapped types lets you create any type transformation you can imagine.
Template literal type keys with as let you generate entire API surface types from a model. Getters<T>, Setters<T>, Validators<T> are all expressible in 3-4 lines of mapped type code.
as never in the key position removes that property from the output type. type StringProps<T> = { [K in keyof T as T[K] extends string ? K : never]: T[K] } keeps only string properties.
Sign in to share your feedback and join the discussion.