Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infer type of callback argument

I cannot get the compiler to know a type of a callback argument.

function test3(fn: (foo: string) => any): any;
function test3(fn: (foo: string, payload: number) => any): any;
function test3(fn: (foo: string, payload: number) => any) {

}

test3((foo) => 1); // Ok, typescript knows "foo" is a string
test3((foo, payload) => 1); // KO, typescript does not infer "foo" nor "payload" type

I don't understand why on the second call, i'd have to manually write the type of foo, but not in the first call.

Can the infer work with these overloads ? If yes, how ? If not, why does it not work ?

like image 802
JeanFoin Avatar asked Dec 09 '25 07:12

JeanFoin


1 Answers

// change the order for more specific type first
function test3(fn: (foo: string, payload: number) => any): any;
function test3(fn: (foo: string) => any): any;
function test3(fn: (foo: string, payload: number) => any) {

}

test3((foo) => 1);
test3((foo, payload) => 1);

Playground

like image 69
Shivam Singla Avatar answered Dec 11 '25 20:12

Shivam Singla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!