0

Let's assume a simplified example (i know in this particular simplification the overloading is not needed, but it's simplified)

EDIT: the first example given was not enough to understand the issue, here is an updated one:

function fn <T>( // Overload signature is not compatible with function implementation.ts(2394)
  fn: (item: T) => T,
): (idx: number) => (src: T[]) => T[]
function fn <T>(
  fn: (item: T) => T,
  idx: number,
): (src: T[]) => T[]
function fn(fn: (x: any) => any, idx?: number) {

}

How in this cas would you qualify the Return type in the implementation.

I've got the compiler complaining on the first definition with ts(2394)and i do not get what i'm doing wrong.

Thank you in advance Seb

1 Answer 1

3

To fix your issue, you need to add a return type to the actual function logic, and not just the definitions.

Due to the fact that each definition overload can return a different result, the actual logic needs some way to support that. The lazy way to do it would be to just return any, however the better way would be to return all the definitions separated by a pipe |. If the return types get too long, just create a declare type definition and declare each one separately.

declare type A<T> = (idx: number) => (src: T[]) => T[]
declare type B<T> =  (src: T[]) => T[]

function fn<T>(fn: (item: T) => T): A<T>
function fn<T>(fn: (item: T) => T, idx: number): B<T>
function fn<T>(fn: (x: any) => any, idx?: number): A<T> | B<T> {

}
Sign up to request clarification or add additional context in comments.

6 Comments

thanks for that (didn't know it). The issue I got is that returns type vary according to definition (in one case returning a function in another returning a function returning a function). I will update my example
When you only have one defined way to use a function it isn't required, however when you have multiple ways that is when it is required due to the fact that it can possibly return multiple types depending on what is passed to the function.
Not sure to see what you're meaning - if possible could you explains it with the updated example? thanks in advance
Basically what you said, your types both return something different. so, you need to tell that function all the types that all the definitions return.
I have also updated my answer with something that should work for you.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.