TypeScript Mapped Types (original) (raw)

Last Updated : 24 Jan, 2025

Mapped types in TypeScript allow you to create new types by transforming the properties of existing types.

type User = { id: number; name: string; email: string; };

type PartialUser = { [P in keyof User]?: User[P]; };

`

**Output:

**const user1: PartialUser = { id: 1 }; const user2: PartialUser = {}; const user3: PartialUser = { id: 2, name: "Alice" };

**More Example of TypeScript Mapped Types

**Creating Readonly Properties

JavaScript `

type User = { id: number; name: string; email: string; };

type ReadonlyUser = { readonly [P in keyof User]: User[P]; };

const user: ReadonlyUser = { id: 1, name: "Alice", email: "alice@example.com" }; user.id = 2;

`

**Output:

Error: Cannot assign to 'id' because it is a read-only property.

**Creating Nullable Properties

JavaScript `

type Product = { name: string; price: number; inStock: boolean; };

type NullableProduct = { [P in keyof Product]: Product[P] | null; };

const product: NullableProduct = { name: "Laptop", price: null, inStock: true };

`

**Output:

{ name: "Laptop", price: null, inStock: true }

Renaming Properties with Template Literals

JavaScript ``

type Person = { firstName: string; lastName: string; };

type PrefixedPerson = { [P in keyof Person as person${Capitalize<P>}]: Person[P]; };

const person: PrefixedPerson = { personFirstName: "John", personLastName: "Doe" };

``

**Output:

{ personFirstName: "John", personLastName: "Doe" }

Best Practices for Using TypeScript Mapped Types