typescript type_error ai_generated true

TS2590: Expression produces a union type that is too complex to represent

ID: typescript/ts-template-literal-type

Also available as: JSON · Markdown
80%Fix Rate
83%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
5 active

Root Cause

Template literal types combining large unions create a combinatorial explosion. Reduce the union size or use a different approach.

generic

Workarounds

  1. 85% success Reduce union size by using branded string types instead of enumerating all values
    // Instead of: type Path = `/${A}/${B}/${C}` (combinatorial explosion)
    // Use branded types:
    type ApiPath = string & { __brand: 'ApiPath' };
    function createPath(a: string, b: string): ApiPath {
      return `/${a}/${b}` as ApiPath;
    }

    Sources: https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html

  2. 82% success Use type validation functions instead of exhaustive literal types
    const validPrefixes = ['get', 'set', 'delete'] as const;
    type Prefix = typeof validPrefixes[number];
    // Validate at runtime instead of creating all combinations
    function isValidMethod(s: string): s is `${Prefix}${string}` {
      return validPrefixes.some(p => s.startsWith(p));
    }

    Sources: https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html

Dead Ends

Common approaches that don't work:

  1. Use @ts-expect-error to suppress the complexity error 75% fail

    The resulting type becomes any/error, losing all type checking for the template literal

Error Chain

Leads to:
Preceded by:
Frequently confused with: