D
D
djEban2022-02-15 20:02:11
typescript
djEban, 2022-02-15 20:02:11

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 - число


For some reason, TS decides that only the last overload is relevant. If I simply call myFuncAs, for example, like this: then everything is fine. Is there any way to fix this to make it work?
((obj?: Obj) => number);

const result = myFuncAs({ apply: true });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2022-02-15
@djEban

TC isn't smart enough for that. He decides this way because when you do SomeType extends BaseTypefor a function argument, inside the function the value of that argument is simple BaseTypeand 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 question

Ask a Question

731 491 924 answers to any question