Conditional type

2 snippets in TypeScript

Also written as type conditional

TSTypeScript

Generics with Conditional Types

TS · Generics
syntax
type Name<T> = T extends Condition ? TrueType : FalseType;
example
type IsArray<T> = T extends any[] ? true : false;

type Test1 = IsArray<string[]>;  // true
type Test2 = IsArray<number>;    // false

// Extracting element types
type ElementOf<T> = T extends (infer E)[] ? E : never;

type StrEl = ElementOf<string[]>;      // string
type NumEl = ElementOf<number[]>;      // number
type NoEl = ElementOf<boolean>;        // never
output
// Conditional types act like type-level if/else

Note When a conditional type receives a union as T, it distributes — the condition is applied to each union member independently. To prevent distribution, wrap both sides in brackets: [T] extends [Condition].

Conditional Types

TS · Advanced Types
syntax
type Result = T extends Condition ? TrueType : FalseType;
example
type IsString<T> = T extends string ? "yes" : "no";

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

// Practical: flatten one level of array
type Flatten<T> = T extends Array<infer Item> ? Item : T;

type Str = Flatten<string[]>;   // string
type Num = Flatten<number>;     // number (not an array, returned as-is)
output
// Conditional types branch on whether T matches a shape

Note Conditional types distribute over naked union type parameters: IsString<string | number> becomes IsString<string> | IsString<number> = "yes" | "no". Wrap in tuple to prevent distribution: [T] extends [string] ? ... : ...