Avoiding Expensive Type Operations
Identify and fix deeply recursive or distributive types.
What Makes a Type Operation Expensive?
Deeply recursive types, large union distributions, and complex infer chains force TypeScript to instantiate many type variants, causing exponential slowdowns.
// Expensive: distributes over every member of a large union
type FilterStrings<T> = T extends string ? T : never;
type Result = FilterStrings<string | number | boolean | null | undefined | ...>;Avoid Excessive Union Sizes
Unions with hundreds of members (e.g., from many string literals) can make type checking very slow. Consider narrowing the domain or using string with validation.
// Expensive
type HugeUnion = "a" | "b" | "c" | /* 200 more ... */ "z";
// Better: string with a runtime check
function isValid(s: string): s is ValidString { return VALID_SET.has(s); }All lessons in this course
- Profiling Slow TypeScript Compilation
- Avoiding Expensive Type Operations
- skipLibCheck and Isolated Declarations
- Type-Checking in CI: Strategies and Tools