Skip to the page

Generics and type-level tools · senior

Mapped types, key remapping and template literal types

A mapped type builds a new object type by looping over keys ({ [K in keyof T]: ... }), with modifiers (?, readonly, -?) and as for renaming keys, often with template literal types like `on${Capitalize<K>}`.

The notes

What you must know

  • { [K in keyof T]?: T[K] } is Partial; -? removes optionality (Required); readonly / -readonly.
  • Key remapping: { [K in keyof T as get${Capitalize<string & K>}]: () => T[K] }.
  • Filtering keys: remap to never to drop a key: as T[K] extends Function ? never : K.
  • Template literal types build string unions: `${'top'|'bottom'}-${'left'|'right'}` gives four combinations.

The red pen

Common traps: mistake → fix

  • Mistake: "mapped types copy methods as-is"

    Fix: they map every key, including methods, unless you filter them out.

Easy to hard

Questions interviewers ask, easy to hard

  1. Implement Partial and Readonly yourself.
  2. How would you type an object of event handlers from an events map?
  3. How do you remove keys whose value is a function?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview