Lesson 20 +10 XP

Conditional Utility Types (Exclude, Extract, ReturnType)

Conditional & Union Utility Types

TypeScript provides utilities to operate on unions, functions, and instance types.

Union & Function Utilities Overview

Utility TypeUsageDescription
Exclude<Union, ExcludedMembers>Union filteringRemoves specified types from a union.
Extract<Union, ExtractedMembers>Union selectionKeeps only types assignable to specified members.
NonNullable<T>Null checkStrips null and undefined from T.
ReturnType<Fn>Function inspectExtracts the return type of a function signature.
Parameters<Fn>Function inspectObtains parameter types of a function as a tuple.

Code Examples

type T0 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"
type T1 = Extract<string | number | boolean, string | number>; // string | number

type T2 = NonNullable<string | number | null | undefined>; // string | number

function getUser() {
  return { id: 101, username: "dev_user" };
}

type UserResult = ReturnType<typeof getUser>; // { id: number; username: string; }

TL;DR

  • Exclude strips union types; Extract keeps matching union types.
  • NonNullable removes null and undefined.
  • ReturnType<typeof fn> captures function return types automatically.