Answer the question
In order to leave comments, you need to log in
Typescript. How to overload an arrow function object?
Hello.
I'm trying to create a main function (myFuncAs), and then a side function (wrapMyFuncAs) that accepts the myFuncAs function config. At the end, the result should be a string, since it passed true, but a number came out.
type Obj<T extends boolean = boolean> = {
apply?: T;
};
type MyFunc = (obj?: Obj) => string | number;
type MyFuncAs = ((obj?: Obj<false>) => number) &
((obj?: Obj<true>) => string) &
((obj?: Obj) => number);
const myFunc: MyFunc = obj => {
if (obj?.apply) return "";
return 5;
};
const myFuncAs = myFunc as MyFuncAs;
const wrapMyFuncAs = <T extends boolean>(obj?: Obj<T>) => myFuncAs(obj);
const result = wrapMyFuncAs({ apply: true }); <---- компилятор показывает, что result - число
((obj?: Obj) => number);
const result = myFuncAs({ apply: true });
Answer the question
In order to leave comments, you need to log in
TC isn't smart enough for that. He decides this way because when you do SomeType extends BaseType
for a function argument, inside the function the value of that argument is simple BaseType
and the automatic inference comes from that. Here, either add overloads to the wrapper with your hands, or try to write a puzzling type, or do without overloads with explicit conditions like:
type MyFuncAs =<T extends boolean> (obj?: Obj<T>) => T extends false ? number : string;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question