Skip to the solution
MediumFrontend10 min read

What are mapped types?

873 views

The problem

Question presented to candidate: "What is a mapped type in TypeScript? Show me how you would write Partial or Readonly yourself, and tell me what else mapped types can do."

What a strong answer should cover:

  • Syntax { [K in Keys]: Type }: a type-level loop over a union of keys that produces one property per key, usually [K in keyof T]: T[K]
  • Changing value types (T[K] | null, functions per property) and the modifiers: adding ? / readonly, removing them with -? / -readonly (the +/- syntax arrived in TypeScript 2.8)
  • That Partial, Required, Readonly, Record and Pick are mapped types in the standard library
  • Homomorphic mapped types (in keyof T, or K extends keyof T) copy the original modifiers, work element-wise on arrays and tuples, and distribute over unions; mapping over an unrelated key union does not keep modifiers
  • Mapped types are compile-time only: building the matching run-time object still needs a loop (and usually one cast); readonly is not enforced at run time
  • Key remapping with as exists for renaming or filtering keys (its own topic)

Code / implementation expected: Yes β€” implement Partial, Readonly or a Mutable helper with a mapped type.

  • mapped-types

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptValue types, modifiers and your own Partial, Readonly and Mutable
TypeScriptHomomorphic mapped types and the run-time side

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 27 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

What are abstract classes?

Continue