Home > database >  Why does function overloading not prompt an error?
Why does function overloading not prompt an error?

Time:11-05

function reverse(x: number): number;
function reverse(x: string): string;
function reverse(x: number | string): number | string {
    return x   '1';
}

Why typescript OK with this function overloading? I want to limit the number input number output and string input string output.

In my function implementation, I deliberately let the number input string output. And I expect that an error message would be thrown when compiling this ts file, but it didn't. Why?

ENVIRONMENT: Without tsconfig.json and tsc version is 4.4.3

CodePudding user response:

Typescript isn't perfect. Check out Github issue #13235 for more info on this particular imperfection.

Basically your implementation function does not know the overload signatures exist. And it is typed to return string | number and it returns string, which is a perfectly valid type to return. It's just that simple.

And yes, in this case you could have a type error at runtime even though the code compiles without error. It's blind spot that there isn't a good way to cover.

Why is it imperfect though? Well, from that Github issue is this quote that sheds a bit more light on it.

There doesn't seem to be much evidence that people are regularly making mistakes here in a way that we could reliably detect without introducing false positives. But the real problem is that any implementation here is going to be at least O(n^2) on the number of signatures, and there are many .d.ts files which have literally dozens of signatures per function. The cost and complexity of checking for "correctness" in overloads every time when the errors are so rare to begin with doesn't seem worth it.

CodePudding user response:

FWIW, in your case you may probably rather use generics.

You want the output type to depend on the input type:

function reverse<T extends string | number>(x: T): T {
  // ...
}
  • Related