Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

TypeScript Conditional and Mapped Types: A Practical Guide

When a domain model evolves, manually duplicated interfaces drift apart. Conditional types select an output according to the input type; mapped types transform properties or variants. This guide builds contracts for forms, events and APIs, explains union pitfalls and tests compiler guarantees without mistaking them for runtime validation.

Published Written by Reading time 10 min read
On this page Contents: quick navigation between sections

Conditional types and infer

conditional.ts

export type ArrayElement<T> = T extends readonly (infer Item)[]
  ? Item
  : never;

export type ToArray<T> = T extends unknown ? T[] : never;

export type WholeArray<T> = [T] extends [unknown] ? T[] : never;

export type IsNever<T> = [T] extends [never] ? true : false;

export type ApiResult<T> = T extends PromiseLike<infer Value>
  ? Value
  : T;

Related article: TypeScript Generics.

The expression T extends U ? X : Y selects a branch according to type assignability, not a JavaScript condition. In the true branch, the compiler can use information from the match. ArrayElement matches mutable and readonly arrays and tuples through readonly (infer Item)[]; other inputs yield never. ApiResult unwraps one PromiseLike layer. Use the built-in Awaited for recursive promise unwrapping. For overloaded functions, ReturnType inference uses the last signature rather than resolving an overload from arguments. [1][3]

Union distribution and never

When the left side of extends is a bare type parameter T, the conditional processes each union member independently. ToArray applied to the union of string and number produces a union of homogeneous arrays. WholeArray wraps both operands in tuples and allows one array to contain both element types. Distribution over never yields never because there are no members to process. IsNever therefore uses tuples. Avoid any at an untrusted boundary: it can undermine conditional inference; use unknown instead. [1]

Mapping properties and modifiers

mapped.ts

import type { IsNever } from "./conditional";

export interface Profile {
  readonly id: string;
  displayName: string;
  bio?: string | null;
  active: boolean;
}

export type FieldErrors<T> = {
  -readonly [Key in keyof T]?: string;
};

export type EditableProfile = Pick<Profile, "displayName" | "bio">;

export type ProfilePatch = Partial<EditableProfile>;

export type RequiredFields<T> = {
  [Key in keyof T]-?: T[Key];
};

export type ChangeHandlers<T> = {
  [Key in keyof T as Key extends string
    ? `on${Capitalize<Key>}Change`
    : never]-?: (value: T[Key]) => void;
};

export type StringFields<T> = {
  [Key in keyof T as T[Key] extends string ? Key : never]: T[Key];
};

type IsString<T> = [T] extends [string] ? true : false;

type IsNonNullableString<T> = IsNever<NonNullable<T>> extends true
  ? false
  : IsString<NonNullable<T>>;

export type NonNullableStringFields<T> = {
  [Key in keyof T as IsNonNullableString<T[Key]> extends true
    ? Key
    : never]: T[Key];
};

Related article: TypeScript Utility Types.

A mapped type iterates over keyof T and obtains a property's value type with T[Key]. Homomorphic mapping preserves modifiers unless changed explicitly. FieldErrors removes readonly and adds optionality so a form stores only existing errors. RequiredFields removes the optional marker without supplying values. With exactOptionalPropertyTypes, omitted bio and bio: undefined have different contracts: ProfilePatch accepts omission or null, but not explicit undefined. Reading an optional field can still yield undefined. [2][4][5]

Key remapping and filtering

The as clause remaps a key, and never excludes it. ChangeHandlers derives names such as onDisplayNameChange while preserving callback parameter types. It intentionally excludes numeric and symbol keys; an optional property's argument can include undefined. StringFields retains fields whose entire type is assignable to string, excluding optional bio. NonNullableStringFields checks the type after removing null and undefined but also rejects never. It preserves the original property type rather than removing null from the value. Avoid collisions in generated names. [2][6]

Discriminated unions and event contracts

unions.ts

export type Payment =
  | { id: string; kind: "card"; lastFour: string }
  | { id: string; kind: "transfer"; reference: string };

export type DistributiveOmit<T, Key extends PropertyKey> =
  T extends unknown ? Omit<T, Key> : never;

export type PublicPayment = DistributiveOmit<Payment, "id">;

export type PaymentHandlers = {
  [Event in PublicPayment as Event["kind"]]: (event: Event) => string;
};

export const handlers = {
  card: (event) => event.lastFour,
  transfer: (event) => event.reference,
} satisfies PaymentHandlers;

export function describePayment(payment: PublicPayment): string {
  switch (payment.kind) {
    case "card": {
      return handlers.card(payment);
    }
    case "transfer": {
      return handlers.transfer(payment);
    }
  }
}

Ordinary Omit<Payment, "id"> operates on the common keys of the union and loses variant-specific fields. DistributiveOmit applies the operation to each variant separately. PaymentHandlers maps the object union by kind and gives each handler the correct argument. satisfies detects missing or incompatible handlers while preserving useful inference. A direct handlers[payment.kind](payment) call may fail type checking because that expression loses correlation. A readable switch narrows the variant without assertions; the example assumes unique kind values. [1][2][7][8]

The boundary between types and runtime

projection.ts

export interface Account {
  id: string;
  displayName: string;
  accessToken: string;
}

export type PublicAccount = Pick<Account, "id" | "displayName">;

export function toPublicAccount(account: Account): PublicAccount {
  return {
    id: account.id,
    displayName: account.displayName,
  };
}

Related article: TypeScript Type Guards and Type Narrowing.

Pick and Omit do not delete object properties. Structural typing permits assignment of Account to PublicAccount, but the token remains in the object and can reach JSON. toPublicAccount explicitly selects allowed fields. Untrusted input requires a runtime parser or schema; backend authorization is still mandatory. readonly does not freeze objects and is shallow. Do not imply security through annotations alone. [3][9]

Testing type contracts

type-tests.ts

import type {
  ApiResult,
  ArrayElement,
  IsNever,
  ToArray,
  WholeArray,
} from "./conditional";
import type {
  ChangeHandlers,
  FieldErrors,
  NonNullableStringFields,
  Profile,
  ProfilePatch,
  RequiredFields,
  StringFields,
} from "./mapped";
import { handlers } from "./unions";
import type { Payment, PublicPayment } from "./unions";

// A generic-function comparison for these concrete type contracts.
type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends
  (<T>() => T extends B ? 1 : 2)
  ? true
  : false;

type Expect<T extends true> = T;

export type ContractTests = [
  Expect<Equal<ArrayElement<readonly [1, 2]>, 1 | 2>>,
  Expect<Equal<ArrayElement<string>, never>>,
  Expect<Equal<ToArray<string | number>, string[] | number[]>>,
  Expect<Equal<WholeArray<string | number>, (string | number)[]>>,
  Expect<Equal<IsNever<never>, true>>,
  Expect<Equal<IsNever<string>, false>>,
  Expect<Equal<keyof StringFields<Profile>, "id" | "displayName">>,
  Expect<
    Equal<keyof NonNullableStringFields<Profile>, "id" | "displayName" | "bio">
  >,
  Expect<Equal<ToArray<never>, never>>,
  Expect<Equal<ApiResult<Promise<number>>, number>>,
  Expect<Equal<ApiResult<Promise<Promise<number>>>, Promise<number>>>,
  Expect<Equal<RequiredFields<Profile>["bio"], string | null>>,
  Expect<Equal<keyof Omit<Payment, "id">, "kind">>,
  Expect<
    Equal<Extract<PublicPayment, { kind: "card" }>["lastFour"], string>
  >,
  Expect<
    Equal<
      Parameters<ChangeHandlers<Profile>["onBioChange"]>[0],
      string | null | undefined
    >
  >,
];

export const errors: FieldErrors<Profile> = {};
errors.id = "Invalid identifier";

export const patch: ProfilePatch = { bio: null };

// @ts-expect-error: explicit undefined is not allowed in this patch.
export const invalidPatch: ProfilePatch = { bio: undefined };

// @ts-expect-error: id is not an editable field.
export const forbiddenPatch: ProfilePatch = { id: "42" };

// @ts-expect-error: a card variant requires lastFour.
export const invalidPayment: PublicPayment = { kind: "card" };

export function invalidDispatch(payment: PublicPayment): string {
  // @ts-expect-error: the indexed call loses variant correlation.
  return handlers[payment.kind](payment);
}

runtime.test.cjs

const { test } = require("node:test");
const assert = require("node:assert/strict");
const { toPublicAccount } = require("./dist/projection.js");
const { describePayment } = require("./dist/unions.js");

test("projects only public account fields", () => {
  // Given
  const account = {
    id: "42",
    displayName: "Ada",
    accessToken: "example-secret",
  };

  // When
  const result = toPublicAccount(account);

  // Then
  assert.deepEqual(result, { id: "42", displayName: "Ada" });
  assert.equal(Object.hasOwn(result, "accessToken"), false);
});

test("describes a card payment", () => {
  // Given
  const payment = { kind: "card", lastFour: "1234" };

  // When
  const result = describePayment(payment);

  // Then
  assert.equal(result, "1234");
});

test("describes a transfer", () => {
  // Given
  const payment = { kind: "transfer", reference: "ABC" };

  // When
  const result = describePayment(payment);

  // Then
  assert.equal(result, "ABC");
});

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "CommonJS",
    "strict": true,
    "exactOptionalPropertyTypes": true,
    "noUncheckedIndexedAccess": true,
    "noEmitOnError": true,
    "outDir": "dist"
  },
  "include": ["*.ts"]
}

Positive tests use Equal and Expect for concrete types. Negative tests use @ts-expect-error to check that forbidden assignments still fail. The compiler reports an unused directive when no error remains, but it does not guarantee a particular diagnostic. Keep one reason for failure in each case and test actual program behavior separately. The Given-When-Then example checks public field projection in Node.js. type-tests.ts is a compile-time fixture only. [10]

When to simplify types and measure cost

Related article: TypeScript tsconfig.json.

Start with built-in utilities and descriptive names. Recursion over arbitrary objects can mishandle Date, functions, arrays, tuples and cycles; if you need DeepReadonly, specify supported structures instead of promising a universal transformation. Template literal cross products and deep recursion can increase compiler work. Measure with tsc --extendedDiagnostics on the same project and compiler version before and after a change. There is no single depth limit that guarantees performance across projects. [6][11]

A useful derived type expresses a domain rule rather than the author's cleverness. Keep type transformations separate from operations performed in JavaScript, test accepted and rejected cases, and add complexity only when it prevents meaningful errors.

TypeScript Conditional Types Mapped Types Generics Type Inference Discriminated Unions Type Testing API Contracts

Frequently asked questions

How does a conditional type differ from if?

It operates during type checking and emits no JavaScript branch.

How do I disable distribution?

Wrap the checked parameter and target in tuples, for example [T] extends [U]. [1]

Does infer recursively unwrap promises?

Not automatically; it depends on the type definition. Use Awaited for this purpose. [3]

Do mapped types change objects?

No. Transforming values requires JavaScript code.

Why does Omit lose union fields?

keyof a union exposes common keys; distribute the operation over its variants. [1][3]

Can type tests replace runtime tests?

No. They verify different contracts: compilation does not prove validation, authorization or operation results.

Sources and references

  1. TypeScript Handbook: Conditional Types↩1↩2↩3↩4↩5↩6↩7↩8
  2. TypeScript Handbook: Mapped Types↩1↩2↩3↩4
  3. TypeScript Handbook: Utility Types↩1↩2↩3↩4↩5↩6
  4. TypeScript 2.8: Conditional Types and Mapped Type Modifiers↩
  5. TSConfig: exactOptionalPropertyTypes↩
  6. TypeScript Handbook: Template Literal Types↩1↩2
  7. TypeScript 4.9: satisfies↩
  8. TypeScript Handbook: Narrowing↩
  9. TypeScript Handbook: Type Compatibility↩1↩2
  10. TypeScript 3.9: ts-expect-error↩
  11. TSConfig: extendedDiagnostics↩

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning