Home > Mobile >  Typescript lint: callback parameters incompatibility when using or
Typescript lint: callback parameters incompatibility when using or

Time:04-12

I found a problem with the type of callbacks parameters:

const foo = (a, func: (a: number | string) => string) => func(a);
      
const a = 12;

foo(a, (z: number) => JSON.stringify(z))

In this rather simple case, I get an error from typescript indicating that my callback is incompatible, due to a type being different from z type:

Argument of type '(z: number) => string' is not assignable to parameter of type '(a: string | number) => string'.
  Types of parameters 'z' and 'a' are incompatible.
    Type 'string | number' is not assignable to type 'number'.
      Type 'string' is not assignable to type 'number'.ts(2345)

Is there a workaround for this ? or do I need to use as ? (which would be inconvenient in my real case)

CodePudding user response:

How feasible it is to use a Function Overload...

function apply_callback(callback_data: number, callback: (data: number) => string): string;
function apply_callback(callback_data: string, callback: (data: string) => string): string;
function apply_callback(callback_data: any, callback: (data: any) => any): any {
    return callback(callback_data);
}

const application1 = apply_callback(3, (d: number) => d.toString());
const application2 = apply_callback("3", (d: string) => d.toString());

console.log(application1, application2);

CodePudding user response:

The types in your arguments do not match (i.e., (number | string) does not match number).

I would change (z: number) => JSON.stringify(z) to (z: number | string) => JSON.stringify(z). So it would be like this:

const foo = (a: number | string, func: (a: number | string) => string) => func(a);

const a = 12;

foo(a, (z: number | string) => JSON.stringify(z))

TypeScript Playground demo

  • Related