Lesson

TypeScript Mapped Types

10 min reading
Free Course

TypeScript Mapped Types: Transforming Every Property Programmatically

A TypeScript mapped type iterates over a union of keys ([K in keyof T]) to construct a new object type systematically. Built-in utilities like Partial<T>, Readonly<T>, and Pick<T, K> are all implemented as mapped types under the hood.

Whenever you want to convert every field of a model into validation flags, getter functions, or nullable form fields without duplicating keys by hand, mapped types keep everything synchronized.

Basic Mapped Types and Modifier Flags (+ / -)

You can add or strip readonly and ? optional modifiers using -readonly or -?.

type Flags<T> = {
  [K in keyof T]: boolean;
};

type Concrete<T> = {
  -readonly [K in keyof T]-?: T[K];
};

interface ConfigDraft {
  readonly host?: string;
  readonly port?: number;
}

type FinalConfig = Concrete<ConfigDraft>; // { host: string; port: number }
type ConfigChecks = Flags<FinalConfig>; // { host: boolean; port: boolean }

const checks: ConfigChecks = { host: true, port: true };
console.log(checks);

Key Remapping with as (TypeScript 4.1+)

Adding an as clause lets you rename keys or filter out unwanted ones using never:

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

Common Mistakes to Avoid

  • Forgetting string & K inside template literal remapping: keyof T includes symbol | number, which template literals reject unless intersected with string.
  • Re-implementing built-in utilities manually: Use Partial<T>, Required<T>, Readonly<T>, and Record<K, V> instead of re-writing them unless customizing behavior.
  • Creating deeply recursive mapped types without depth limits: Deeply nested DeepPartial<T> types should stop on functions, Dates, and primitives so they do not break tsc performance.

Frequently Asked Questions

What does -? mean inside a mapped type?

It removes the optional ? modifier from every property, making all properties required (exactly how Required<T> works).

How do I filter properties by their value type using a mapped type?

Combine as with a conditional check: [K in keyof T as T[K] extends string ? K : never]: T[K].

Can mapped types preserve homomorphic modifiers?

Yes. Mapping directly over [K in keyof T] automatically preserves existing readonly and ? modifiers from T unless overridden.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
TypeScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum