HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptModeratepending

TypeScript Mapped Types and Template Literal Types

Submitted by: @anonymous··
0
Viewed 0 times
mapped typestemplate literal typeskeyofconditional typesTypeScript

Problem

Need to derive new types from existing ones systematically without manually maintaining duplicate type definitions.

Solution

Mapped and template literal type patterns:

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

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

// Readonly version
type Readonly<T> = { readonly [K in keyof T]: T[K] };

// Pick specific keys
type UserPreview = Pick<User, 'id' | 'name' | 'avatar'>;

// Remap keys with 'as'
type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]
};
// { getName: () => string; getAge: () => number; }

// Template literal types
type EventName = `on${Capitalize<'click' | 'focus' | 'blur'>}`;
// 'onClick' | 'onFocus' | 'onBlur'

// Conditional mapped types
type NonFunctionKeys<T> = {
  [K in keyof T]: T[K] extends Function ? never : K
}[keyof T];

type DataOnly<T> = Pick<T, NonFunctionKeys<T>>;

// Deep partial
type DeepPartial<T> = {
  [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K]
};

Why

Mapped types eliminate manual synchronization between related types. When the source type changes, all derived types update automatically.

Gotchas

  • Template literal types can create huge unions - TypeScript limits to 100,000 members
  • Recursive mapped types can hit depth limits - add explicit base cases

Context

Advanced TypeScript type manipulation

Revisions (0)

No revisions yet.