简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM