Skip to the solution
HardFrontend10 min read

What is key remapping in mapped types?

1.1k views

The problem

Question presented to candidate: "In a mapped type you can write as after the key. What does that do? Show me how you would generate getter names like getName from a Person type, and how you would drop some keys."

What a strong answer should cover:

  • The as clause, { [K in keyof T as NewKey]: ... }, computes the output key from each input key; added in TypeScript 4.1 together with template literal types
  • Renaming with template literal types and the intrinsic string helpers: `get${Capitalize<string & K>}`, and why string & K is needed (keys can be number or symbol)
  • Filtering: a key remapped to never is dropped, by key (Exclude<K, "kind">) or by value (T[K] extends V ? K : never)
  • Mapping over a union of objects rather than keys, e.g. an event union to an onClick / onKey handler map
  • Behaviour details: modifiers are still copied from keyof T, keys that collide merge into a union, and a filtering as turns an array or tuple into an object of all its members
  • The run-time object still has to be built by hand with matching names

Code / implementation expected: Yes β€” a Getters<T> type and a filter that keeps only properties of a given value type.

  • key-remapping

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.

TypeScriptRenaming and filtering keys with as
TypeScriptstring & K, collisions, unions of objects and tuples

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 66 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 nextHard

How would you build a DeepPartial type?

Continue