gvergnaud / ts-pattern

🎨 The exhaustive Pattern Matching library for TypeScript, with smart type inference.
MIT License
12.51k stars 135 forks source link

Perf: support exhaustive match on larger unions #214

Closed gvergnaud closed 10 months ago

gvergnaud commented 10 months ago

in v5.0.6, .exhaustive() might throw a "recursion is possibly infinite" error on input types with a distributed cardinality of more than |500|. For example this type:

type State = 'idle' | 'loading' | 'success' | 'error' | 'partial_result'

type Input = {
  a: State,
  b: State,
  c: State,
  d: State,
};

has a cardinality of 5^4 == 625 entries. If your pattern matches all keys of this object and you use .exhaustive(), TS-Pattern will distribute this type and turn it into a union of 625 objects in order to compute unhandled cases. This currently reaches typescript recursion limit. This PR makes slight changes to avoid reaching limit as early.