# Mapped Types

> The mapped types in TypeScript create new types by transforming each property of an existing type.

## How do mapped types work in TypeScript?

The types that iterate over keys with the `in` operator, usually `keyof`, to build a new type, for example `{ [K in keyof T]: boolean }`. Support adding or removing `readonly` and `?` modifiers and remapping keys with `as`.

- Topic: Advanced Types
- Type: concept

## Example

Wrong:

```ts
type User = { id: string; name: string };
type UserGetters = {
  getId: () => string;
  getName: () => string;
};
```

Right:

```ts
type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type UserGetters = Getters<User>;
```

Key remapping with `as` derives the getter names and return types from `User` instead of copying them.

## Common mistakes

- Writing `Capitalize<K>` on `keyof T` and getting an error because keys may be numbers or symbols.

## Key points

- Mapped types iterate with `[K in keyof T]`, and modifiers are changed with `-readonly` or `-?`.
- Keys are renamed or filtered with `as`, e.g. `as Exclude<K, 'id'>`.
- Built-in `Partial`, `Required`, `Readonly`, `Pick` and `Record` are used before writing a custom mapped type.

## Interview questions

### How do I remove readonly or optional with a mapped type?

Prefix the modifier with minus: `-readonly [K in keyof T]-?: T[K]`.

### How do I drop some keys in a mapped type?

Remap them to `never`, e.g. `[K in keyof T as K extends 'id' ? never : K]: T[K]`.

## Related cards

- [keyof](https://wonderium.dev/ts/keyof.md)
- [`Partial<T>`](https://wonderium.dev/ts/partial.md)
- [`Record<Keys, T>`](https://wonderium.dev/ts/record.md)
- [Indexed Access Types](https://wonderium.dev/ts/indexed-access-types.md)
- [Template Literal Types](https://wonderium.dev/ts/template-literal-types.md)

---

- Level: [TypeScript](https://wonderium.dev/ts.md)
- HTML version: https://wonderium.dev/ts/mapped-types
- Last updated: 2026-11-25
