Is there a way for TypeScript to validate the function body against function overloads? Despite having multiple signatures, it seems that the function implementation is not being checked properly:
function a(input: string): string
function a(input: number): number
function a(input: string | number): string | number {
if (typeof input === "string") return 42
return "banana"
}
Could the issue be with my third signature? It appears that the catch-all signature is not considered in the resulting type, and I'm struggling to declare the function without running into an
Overload signature is not compatible with function implementation.
error.
typeof a = {
(input: string): string;
(input: number): number;
}
I might consider using the more explicit intersect type instead:
type C = ((input: number) => number) & ((input: string) => string)
However, I am unsure how to implement a function that satisfies this without resorting to overload syntax, which feels somewhat forced. I have explored this further in my question onOverloaded function type in typescript.
Edit: The initial example provided is a basic illustration. You can test it with the following:
const number: number = a(0)
console.log("number", typeof number, number)
This will output number string banana
const string: string = a("")
console.log("string", typeof string, string)
This will output string number 42
Edit 2: My query does not overlap with the discussion onOverloaded function type in typescript. I am specifically interested in typechecking the function's implementation across all overloads, while the other question focuses on creating a new function that matches a given overload type.