never vs undefined in Conditionals
You'll learn: Why never removes a branch entirely while undefined keeps it, and when each behavior is desired in conditional types.
The Core Distinction
When building conditional types, the difference between returning never and returning undefined dramatically changes how TypeScript treats your type logic:
never: Completely eliminates a branch from a union, as if that case doesn't existundefined: Keeps the branch in the union, but with a value ofundefined
Think of it like pruning a tree: never cuts off the branch entirely, while undefined leaves a stub labeled "nothing here."
How Each Behaves in Unions
When conditional types evaluate to never, TypeScript performs union elimination:
type OnlyStrings<T> = T extends string ? T : never;
// never gets eliminated from the union automatically
type Result = OnlyStrings<string | number | boolean>;
// Result = string (number and boolean branches removed)
But with undefined, the branch survives:
type MaybeStrings<T> = T extends string ? T : undefined;
type Result = MaybeStrings<string | number | boolean>;
// Result = string | undefined (all branches kept)
When to Use never
Use never when you want to filter or exclude certain types from consideration. This is perfect for building utility types that remove unwanted cases:
type FilterFunctions<T> = T extends Function ? never : T;
type Clean = FilterFunctions<string | number | (() => void)>;
// Clean = string | number (function eliminated)
When to Use undefined
Use undefined when you want to preserve all branches but signal absence in some cases. This is useful when the presence of undefined itself carries meaning:
type SafeLookup<T, K> = K extends keyof T ? T[K] : undefined;
type Result = SafeLookup<{name: string}, "age">;
// Result = undefined (branch exists, value is undefined)
Key Takeaway: Use never to eliminate branches from unions (filtering), and undefined to keep branches while indicating "no value" (optional presence). The choice determines whether TypeScript sees one possibility or multiple.