Skip to content

Overload/implementation compatibility forces users to use default to 'any' return type #5350

Closed
@WreckedAvent

Description

@WreckedAvent

To be illustrative of the issue, imagine a toy class:

class Test {
    something(x: number): number;
    something(x: string): string;
    something(x: number | string) {
        if (typeof x === "number") {
            return x * 2;
        } else {
            return x + ' is a string';
        }
    }
}

This will not compile, since it is unable to find the best common type between 'number' and 'string'. If modified like this:

    something(x: number | string): number | string {
        if (typeof x === "number") {
            return x * 2;
        } else {
            return x + ' is a string';
        }
    }

then the earlier defined overload fails, saying it is not compatible with the signature of the implementation function.

The only way it seems like you can get this to compile is by simply defining it as any:

    something(x: number | string): any {
        if (typeof x === "number") {
            return x * 2;
        } else {
            return x + ' is a string';
        }
    }

This now compiles, but now we have lost any benefit from being in the typescript world, since my implementation could just as easily do this:

    something(x: number | string): any {
        return { some: 'object' };
    }

Is there a way around this or some solution I'm not seeing?

Note: I am aware that this can be typed without overloads at all, using union types, but this does not really satisfy to me, since the calling code will have to do typeof checks or a typecast.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions