2
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

2 Answers 2

2

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.

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

1 Comment

Thank you for such detailed information. I think I can accept this imperfection now.
1

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 {
  // ...
}

3 Comments

How can this work? function reverse<T extends string | number>(x: T): T { return 1 + x; } Error message is "Operator '+' cannot be applied to types 'number' and 'T'"
Seems to me that you fall in this scenario: stackoverflow.com/questions/54470329/…

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.