Common Patterns with Exclude, Extract, and NonNullable
You'll learn real-world scenarios where Exclude, Extract, and NonNullable solve practical typing problems.
The Core Idea
While these three utilities might seem abstract, they shine in everyday situations: filtering out unwanted types from unions, selecting only relevant types, and ensuring values aren't null or undefined. Let's see how they work together in real codebases.
Pattern 1: Event Handler Type Safety with Extract
type AppEvent =
| { type: 'login'; userId: string }
| { type: 'logout' }
| { type: 'error'; message: string }
| { type: 'click'; x: number; y: number };
// Only handle user-related events
type UserEvent = Extract<AppEvent, { type: 'login' | 'logout' }>;
// Result: { type: 'login'; userId: string } | { type: 'logout' }
Pattern 2: Removing Optional States with Exclude
type Status = 'pending' | 'success' | 'error' | null | undefined;
// Only definite statuses for display logic
type DefiniteStatus = Exclude<Status, null | undefined>;
// Result: 'pending' | 'success' | 'error'
Pattern 3: Filtering After Array Operations with NonNullable
type MaybeUser = { name: string } | null | undefined;
function getUserNames(users: MaybeUser[]): NonNullable<MaybeUser>[] {
return users.filter((u): u is NonNullable<MaybeUser> => u !== null && u !== undefined);
}
Pattern 4: Combining All Three
type ApiResponse = string | number | null | undefined | { error: string };
// Extract only successful primitive responses, excluding nullish values
type SuccessResponse = NonNullable<Exclude<ApiResponse, { error: string }>>;
// Result: string | number
Key Takeaway: Exclude filters out unwanted union members, Extract selects specific ones, and NonNullable removes null/undefined—combine them to create precise types from messy real-world unions.