TypeScript Type Complexity
Grades the most complex declaration in a file: deep generic nesting, stacked conditional types, eagerly-expanded recursion, and wide unions and intersections.
TypeScript's type system is Turing-complete and easy to over-engineer. Conditional types that recurse, generics nested five deep and long chains of type-level branching slow down the language server, blow up the inferred type display, and make error messages incomprehensible. This analysis surfaces type-level complexity hotspots so they can be simplified or extracted.
Complexity is measured per declaration, and the score follows the most complex declaration in the file (three quarters) and the 90th percentile of all of them (one quarter). A file of thirty trivial generic functions is thirty simple declarations and scores the same as a file with one; a sum over the file would only measure its length. What every ordinary declaration has is free: nesting two generics deep (Promise<Map<string, User>>), a three-member union, a two-part intersection and one type parameter.
Three things that look complex and are not are left alone. A flat union of string literals has no structure to follow: its members count logarithmically, and no union draws "use a discriminated union" advice from this analysis (an object union with no discriminant is reported by ts-type-guards). A type that refers to itself through an object, array or tuple member (a tree, the JSON type) is resolved lazily by the compiler and is not reported as recursion; only recursion through a conditional type is. And a reference without type arguments is a leaf, not a level of generic nesting.
Severity guide
- info
- A complex type construct is present but at acceptable scale.
- warning
- A type construct will impact compile speed or error readability; consider simplifying.
- critical
- Not currently emitted by this analysis.
Remediation
Name the intermediate types of a deep generic; split a declaration that chains conditional types into helpers; bound recursive conditional types.
Name the intermediate types of a deeply nested generic so each level reads on its own. Split a declaration that chains several conditional types into named helper types. Make sure a recursive conditional type reaches a base case for every input, and prefer a built-in such as Awaited<T> where one exists.