goenning
goenning

Reputation: 6654

How to use function overload with classes in TypeScript?

Given following TypeScript code

class NumberChecker { }
class StringChecker { }
class Component {}
class ComponentChecker { }
class Grid { }
class GridChecker { }

function check(element: number): NumberChecker;
function check(element: string): StringChecker;
function check(element: Grid): GridChecker;
function check(element: Component): ComponentChecker {
    if (typeof element === 'number') {
        return new NumberChecker();
    }
    if (typeof element === 'string') {
        return new StringChecker();
    }
    if (element instanceof Component) {
        return new ComponentChecker();
    }
    if (element instanceof Grid) {
        return new GridChecker();
    }
}

const a = check(2); // a is NumberChecker
const b = check('sdf'); // b is StringChecker
const c = check(new Component()); // c is GridChecker
const d = check(new Grid()); // d is GridChecker

Why c and d are both GridChecker? I was expecting c to be ComponentChecker.

Link to Playground

Upvotes: 1

Views: 51

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164139

The signature of the actual implementation needs to cover all of the options, in your case, it should be:

function check(element: number): NumberChecker;
function check(element: string): StringChecker;
function check(element: Grid): GridChecker;
function check(element: Component): ComponentChecker;
function check(element: number | string | Grid | Component) {
    // ...
}

Then the type for:

const c = check(new Component());

Is ComponentChecker.

But again, only if the different classes don't have the same structure.

Upvotes: 3

Related Questions