JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstypescript
PrevNext
typescript
senior
mapped-types

How do mapped types work in TypeScript?

mapped-types
keyof
key-remapping
modifiers
advanced
Quick Answer

Mapped types transform existing types by iterating over their keys using 'in keyof' syntax. They can modify properties (make optional, readonly), rename keys, and filter properties. Built-in utilities like Partial, Required, and Pick use mapped types.

Detailed Explanation

Mapped Type Syntax:

  • { [K in keyof T]: T[K] }: Basic mapping
  • + / - modifiers for optional and readonly
  • as clause for key remapping
  • Template literal keys for renaming

Modifiers:

  • readonly: Make properties readonly
  • ?: Make properties optional
  • -readonly: Remove readonly
  • -?: Remove optional (make required)

Key Remapping:

  • as clause to filter or rename keys
  • Template literals for pattern-based renaming
  • never to filter out keys

Code Examples

Basic mapped types
// Identity mapping (copies type)
type Identity<T> = {
  [K in keyof T]: T[K];
};

// Make all properties optional (Partial)
type MyPartial<T> = {
  [K in keyof T]?: T[K];
};

// Make all properties required (Required)
type MyRequired<T> = {
  [K in keyof T]-?: T[K];  // -? removes optional
};

// Make all properties readonly (Readonly)
type MyReadonly<T> = {
  readonly [K in keyof T]: T[K];
};

// Remove readonly
type Mutable<T> = {
  -readonly [K in keyof T]: T[K];
};

// Example usage
interface User {
  readonly id: number;
  name?: string;
  email: string;
}

type MutableUser = Mutable<User>;
// { id: number; name?: string; email: string } - id no longer readonly

type RequiredUser = MyRequired<User>;
// { readonly id: number; name: string; email: string } - name required

Resources

TypeScript - Mapped Types

docs

Related Questions

How do conditional types work in TypeScript?

senior
conditional-types

What are template literal types and how do you use them?

senior
template-literal-types
Previous
How do conditional types work in TypeScript?
Next
What are template literal types and how do you use them?