Codectionary / Developer documentation / TypeScript

Conditional Types

A conditional type selects between two types based on a condition, using syntax that mirrors JavaScript's ternary operator: T extends U ? X : Y. This lets you build types that adapt based on the shape of another type, forming the foundation for many of TypeScript's built-in utility types.

Syntax

T extends U ? TrueType : FalseType

Examples

A Basic Conditional Type

Selecting a type based on whether another type satisfies a condition.

type IsString<T> = T extends string ? "yes" : "no";

type A = IsString<string>;  // "yes"
type B = IsString<number>;  // "no"

type ExtractArray<T> = T extends (infer U)[] ? U : T;
type C = ExtractArray<number[]>; // number - extracted the element type
type D = ExtractArray<string>;    // string - unchanged, T was not an array

Practical Use: A Custom Utility Type

Building a type that filters out null/undefined, a common real-world pattern.

type NonNullable<T> = T extends null | undefined ? never : T;

type A = NonNullable<string | null>;      // string
type B = NonNullable<number | undefined>;  // number
// This is actually one of TypeScript's own built-in utility types

Best practices

  • Use conditional types when a type needs to adapt its shape based on characteristics of another type, similar to overloaded function behavior at the type level
  • Study TypeScript's own built-in utility types (like NonNullable, ReturnType) - many are implemented using conditional types and are excellent learning examples
  • Keep conditional types as simple as possible - deeply nested conditional chains become genuinely difficult for anyone (including future you) to read
  • Combine conditional types with infer when you need to extract and reuse part of the matched type, not just branch based on it

At a glance

Purpose
Static types for JavaScript
File extension
.ts ยท .tsx
Runs in
Compiled to JavaScript
Usually used with
JavaScript and its ecosystem

Specifications & further reading

Related TypeScript documentation