1

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

3
  • 1
    You should try that again with different definitions. Those Component and Grid are currently compatible. Commented Jul 16, 2017 at 15:11
  • Just tried adding different properties to both classes and got compilation error 'Overload signature is not compatible with function implementation.' which I don't know how to solve. Commented Jul 16, 2017 at 15:17
  • But that's a good point. Each Checker class will have different methods. If I try to add them, I get even more compilation errors. I though that return types didn't have to be compatible between each other. Commented Jul 16, 2017 at 15:19

1 Answer 1

3

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.

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

Comments

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.