Gricey
Gricey

Reputation: 1441

Why will Typescript allow incorrect overloaded function returns?

In this answer a Typescript maintainer gives a simple example of how overloading works in Typescript and how it differs to languages with actual overloading.

However modifying their example to the following still compiles:

function numberStringSwitch(x: string): number;
function numberStringSwitch(x: number): string;
function numberStringSwitch(x: string | number) {
    return x;
}

This seems to me like it shouldn't be valid; why is it allowed? How do I make this example fail to compile like I'd expect?

Playground link, TS 3.6.3

Upvotes: 1

Views: 62

Answers (1)

zhuber
zhuber

Reputation: 5524

It should be pretty simple - there are 2 possible inputs to your numberStringSwitch method - string or number - and that is exactly what unions are in typescript. This means that you can write your "implementation" method using union signature which is string | number - it's important because when you are writing body of your method you need to have safely typed input which represents union of all your overload inputs (in this case either string or number). You could of course use any like they did, but it's union is also an option (honestly more readable option for me).

You can try to use change your input to something that is not in your overloads methods and you'll get error

// error
function numberStringSwitch(x: string | Date) {
    return x;
}

But if you add another overload with Date and add it's parameter type to final union, it works:

// works
function numberStringSwitch(x: string): number;
function numberStringSwitch(x: number): string;
function numberStringSwitch(x: Date): string;
function numberStringSwitch(x: string | number | Date) {
    return x;
}

Upvotes: 1

Related Questions