TypeScript · Types that pay for themselves
What are mapped types?
Short answer
A mapped type builds a new object type by iterating over a union of keys. Modifiers and key remapping let you make properties optional, readonly or renamed while preserving the source shape.
A mapped type uses a syntax similar to an index signature but iterates over a key union. For each key, it computes a property type from the original type. The compiler treats it as a transformation of the source shape, so related types stay in sync when the source changes.
type User = { id: number; name: string };
type Optional<T> = { [K in keyof T]?: T[K] };
type ReadonlyUser = { readonly [K in keyof User]: User[K] };
type Nullable<T> = { [K in keyof T]: T[K] | null };
type PartialUser = Optional<User>;Modifiers and remapping
- Add ? to make properties optional, or -? to remove optionality
- Add readonly, or -readonly to remove it
- Use as to remap keys, often with template literal types
- A homomorphic mapped type preserves modifiers and works on arrays and tuples
- Mapped types are the implementation behind Partial, Required, Readonly and Pick
Mapped types are powerful but easy to overuse. A deeply recursive mapped type can produce very large unions and slow the compiler. Keep them shallow unless the problem genuinely requires recursion, and test the resulting types at the call site.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1How do you remove readonly from every property?
- 2What does a homomorphic mapped type preserve?
- 3How does key remapping with as work?
- 4Why can recursive mapped types be expensive?
Say it in the interview
A mapped type iterates over a union of keys and produces a new object type. I use it to make properties optional, readonly or nullable without repeating the original shape. Homomorphic mapped types preserve modifiers and also work on arrays and tuples. Key remapping with as is powerful, but I keep mapped types small because heavy type-level code is hard to debug.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live TypeScript mock interview and get scored feedback on depth, clarity and confidence.