Create Explicit and Readable Type Declarations with TypeScript mapped Type Modifiers

InstructorRares Matei

Share this video with your friends

Send Tweet

Using the optional “+” sign together with mapped type modifiers, we can create more explicit and readable type declarations. We can also use the “-” (minus) sign to remove optional declarations from properties.

Eduardo Valenzuela
~ 6 years ago

Hi, quick question, in which cases we would need to avoid modifying an interface itself and choosing modify it through a type?

Rares Mateiinstructor
~ 6 years ago

Hi, Eduardo! If you can modify your interface directly then I'd recommend going for that!

Mapped type modifiers are useful if you either:

  • have an interface you can't modify directly (like one from a library)
  • have an interface that you want to continue using for some purposes, and create a slight variation of it (using mapped type modifiers) to use for other purposes

In both cases, mapped type modifiers "follow" the shape of the original interface, even if it changes/gets modified in the future, and just augment it based on the rules you specify.

James Gelok
~ 4 years ago

there's a typo here: readonly [K in key of IPet]: IPet[K]; should be readonly [K in keyof IPet]: IPet[K];