#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read
Question 17 of 48hard

What are Mapped Types in TypeScript?

Transforming types with mapped types.

What You'll Learn

  • What mapped types are
  • How to create them
  • Common patterns

What are Mapped Types?

Mapped types transform properties of an existing type to create a new type.

code.tsTypeScript
// Basic syntax
type Mapped<T> = {
  [K in keyof T]: T[K];
};

Making Properties Optional

code.tsTypeScript
type MyPartial<T> = {
  [K in keyof T]?: T[K];
};

interface User {
  name: string;
  age: number;
}

type OptionalUser = MyPartial<User>;
// { name?: string; age?: number; }

Making Properties Readonly

code.tsTypeScript
type MyReadonly<T> = {
  readonly [K in keyof T]: T[K];
};

Transforming Property Types

code.tsTypeScript
// Make all properties nullable
type Nullable<T> = {
  [K in keyof T]: T[K] | null;
};

// Make all properties getters
type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};

interface Person {
  name: string;
  age: number;
}

type PersonGetters = Getters<Person>;
// { getName: () => string; getAge: () => number; }