typescript type_error ai_generated true

TS2345: Argument of type 'X' is not assignable to parameter of type 'Y'

ID: typescript/ts2345-argument-not-assignable

Also available as: JSON · Markdown
87%Fix Rate
89%Confidence
255Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
5 active

Root Cause

Function argument doesn't match the expected parameter type.

generic

Workarounds

  1. 90% success Transform the argument to match the expected type before passing
    // Convert string to number:
    parseInt(value, 10)
    // Convert to expected shape:
    const arg: ExpectedType = {
      ...input,
      missingField: defaultValue
    };
    fn(arg);

    Sources: https://www.typescriptlang.org/docs/handbook/2/narrowing.html

  2. 85% success Use function overloads or generics to accept multiple types safely
    Use function overloads or generics to accept multiple types safely

    Sources: https://www.typescriptlang.org/docs/handbook/2/generics.html

  3. 87% success Create a type guard to narrow the type before the function call
    function isString(value: unknown): value is string {
      return typeof value === 'string';
    }
    
    const input: string | number = getValue();
    if (isString(input)) {
      // input is narrowed to string here
      processString(input);
    }

    Sources: https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates

Dead Ends

Common approaches that don't work:

  1. Cast the argument with 'as ExpectedType' 72% fail

    Type assertion can hide real bugs if the runtime value doesn't match

  2. Change the function parameter to accept any 80% fail

    Removes type safety for all callers

Error Chain

Leads to:
Preceded by:
Frequently confused with: