Willem van der Veen
Willem van der Veen

Reputation: 36600

What is a mapped type and how is this useful?

How does it work? When should I use it?

Upvotes: 2

Views: 3769

Answers (1)

Willem van der Veen
Willem van der Veen

Reputation: 36600

Typescript mapped types:

In Typescript we sometimes want to build types based on other types. Mapped types allow us to generate new types based on existing types in a very concise manner which makes us adhere to the don't repeat yourself principle


Custom properties:

  • Problem: We don't know all the properties of the object type beforehand
  • Solution: We can declare custom properties and type them using the following syntax:

type customProperties = {
  [key: string]: string | boolean;
};

const conforms: customProperties = {
  str: 'foo',
  bool: true,
  // int: 123 > Error Type 'number' is not assignable to type 'string | boolean'.
};

Mapped types:

  • Problem: We to base an object type on another type and we don't want to define all the properties in every type
  • Solution: We can declare custom properties and type them using the following syntax:

type Person = {
  name: string;
  age: string;
};

// Demo only >> TS has a builtin Readonly, use that
type myReadonly<Type> = {
  readonly [Property in keyof Type]: Type[Property];
};

// Demo only >> TS has a builtin Partial, use that
type myPartial<Type> = {
  [Property in keyof Type]?: Type[Property];
};

type ReadonlyPerson = myReadonly<Person>
type PartialPerson  = myPartial<Person>

Note that mapped types is using the syntax []: type of custom properties. the difference between the custom properties and the mapped type is the following:

  • The mapped type iterates over the properties of an existing type using generics and the [Property in keyof Type] syntax. It maps all the properties of the existing type to the new type which you can customize according to your needs.
  • Custom properties lets you type the properties of the object which you don't know in advance. This is useful when we don't know what the object will exactly look like. The object can properties which are not known at the time of writing the code.

Upvotes: 5

Related Questions