Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Infer type inside switch/case statement using instanceof #20957

Closed
maxkoretskyi opened this issue Jan 2, 2018 · 2 comments
Closed

Infer type inside switch/case statement using instanceof #20957

maxkoretskyi opened this issue Jan 2, 2018 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@maxkoretskyi
Copy link

maxkoretskyi commented Jan 2, 2018

I'm not sure if it's a bug or a feature request. I have the following simple example:

class T1 { a: string; }
class T2 { b: string; }

f(new T1());

function f(p: T1 | T2) {
    switch(true) {
        case (p instanceof T1) : {
            console.log(p.a); // Error:(12, 27) TS2339:  Property 'a' does not exist on type 'T2'
            break;
        }
        case (p instanceof T2) : {
            console.log(p.b); // Error:(12, 27) TS2339:  Property 'b' does not exist on type 'T1'
            break;
        }
    }
}

I get an error on the logging lines because typescript can't know whether p is of type T1 or T2. However I use instanceof operator so it should be able to infer the correct type as it works fine with if statement:

function f(p: T1 | T2) {
    if (p instanceof T1) {
        console.log(p.a);   // no error
    }
}

TS version 2.6.2

I know I can fix it using explicit type casting like this:

console.log((<T1>p).a);

but that seems redundant. Also interesting that type guard doesn't work:

function isT1(t: any): t is T1 {
    return (t instanceof T1);
}

function f(p: T1 | T2) {
    switch(true) {
        case (isT1(p)) : {
            console.log(p.a); // Error:(12, 27) TS2339:  Property 'a' does not exist on type 'T2'
            break;
        }
@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jan 2, 2018
@RyanCavanaugh
Copy link
Member

Duplicate #8934

@typescript-bot
Copy link
Collaborator

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

@microsoft microsoft locked and limited conversation to collaborators Jul 3, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants