On this page
  1. Conditional, Mapped & Template Literal Types
  2. Contents
  3. Conditional Types & infer
  4. Mapped Types & Key Remapping (as)
  5. Template Literal Types

Conditional, Mapped & Template Literal Types

Prev: Generics, Constraints & Variance | Up: type_system | Next: Type-Checking & Erasure Pipeline
Rel: infer, typescript/utility_types
Ref: TypeScript Handbook — Mapped Types
Tags: #public #web #typescript #type-system #metaprogramming


Contents


Conditional Types & infer

Conditional types branch on assignability (T extends U ? X : Y) and distribute automatically over naked union type parameters (ToArray<string | number> -> string[] | number[]; wrap in [T] extends [U] to disable distribution):

type UnwrapArray<T> = T extends readonly (infer U)[] ? U : T;
type Item = UnwrapArray<string[]>; // string

Mapped Types & Key Remapping (as)

Transform every key of an object type, adding/removing readonly or ? modifiers (-readonly, -?) and renaming keys with as:

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

type UserGetters = Getters<{ id: number; name: string }>;
// { getId: () => number; getName: () => string }

Template Literal Types

Combine unions inside backtick type strings to generate finite string sets:

type Axis = "x" | "y";
type EventName = `pointer:${Axis}:${"start" | "end"}`;
// 'pointer:x:start' | 'pointer:x:end' | 'pointer:y:start' | 'pointer:y:end'

Linked from

Related notes