typescript type_error ai_generated true

Type 'T' is not assignable to type 'T extends U ? X : Y'

ID: typescript/ts-conditional-type-error

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
5 active

Root Cause

Conditional types are not resolved when the type parameter is still generic. Use type narrowing or overloads instead.

generic

Workarounds

  1. 88% success Use function overloads instead of conditional return types
    function process(input: string): number;
    function process(input: number): string;
    function process(input: string | number): number | string {
      return typeof input === 'string' ? input.length : String(input);
    }

    Sources: https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads

  2. 82% success Use Extract/Exclude utility types to simplify conditional types
    type StringOnly = Extract<MyUnion, string>;
    type NonString = Exclude<MyUnion, string>;

    Sources: https://www.typescriptlang.org/docs/handbook/utility-types.html

Dead Ends

Common approaches that don't work:

  1. Add type assertions at every conditional type usage 70% fail

    Assertions bypass the type system; if the condition is wrong, runtime errors occur

Error Chain

Leads to:
Preceded by:
Frequently confused with: