Skip to content
typescript questions

TypeScript · 7 of 10senior~1 min

What are mapped types and template literal types?

#types#advanced

Mapped Types

Mapped types create new types by iterating over the keys of an existing type.

ts
// make all properties optional (like Partial<T>) type Optional<T> = { [K in keyof T]?: T[K]; }; // make all properties nullable type Nullable<T> = { [K in keyof T]: T[K] | null; };

With remapping via as

ts
type Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]; }; type User = { name: string; age: number }; type UserGetters = Getters<User>; // { getName: () => string; getAge: () => number }

Template Literal Types

Build string types by combining other types.

ts
type Direction = 'top' | 'right' | 'bottom' | 'left'; type CSSPadding = `padding-${Direction}`; // 'padding-top' | 'padding-right' | 'padding-bottom' | 'padding-left'

Practical example

ts
type EventName<T extends string> = `on${Capitalize<T>}`; type ClickEvent = EventName<'click'>; // 'onClick' type ChangeEvent = EventName<'change'>; // 'onChange'

Together mapped types and template literals allow generating entire API surfaces from a single source of truth.

updated

did you know it?

related questions