A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/typescript/typescript-mapped-types/ below:

TypeScript Mapped Types - GeeksforGeeks

TypeScript Mapped Types

Last Updated : 24 Jan, 2025

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

JavaScript
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

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4