Skip to content

Type narrowing for fields #1721

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

Closed
laszlojakab opened this issue Jan 19, 2015 · 3 comments
Closed

Type narrowing for fields #1721

laszlojakab opened this issue Jan 19, 2015 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@laszlojakab
Copy link

Hi!

Type narrowing is not working (not supported?) for fields (VS2013, TypeScript 1.4).

class O1Cls {
    x: any;
}

class O2Cls {
    y: any;
}

interface Options {
    opt: O1Cls|O2Cls;
}

class MyClass {
    constructor(options: Options) {
        if (options.opt instanceof O1Cls) {
            console.log(options.opt.x); // Error: Property 'x' does not exists on type 'O1Cls | O2Cls'
        }

        var opt = options.opt;
        if (opt instanceof O1Cls)
        {
            console.log(opt.x); // OK
        }
    }
}

Will it be supported or is this a "by design" behaviour?

@lbguilherme
Copy link

Fields can have getters, so options.opt may return different things each time it is evaluated. Not sure if it can be statically checked.

@laszlojakab
Copy link
Author

@GuilhermeBernal: since i wrote this I've already noticed that. So probably it is not an issue.

@RyanCavanaugh
Copy link
Member

See also #1706

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jan 19, 2015
@microsoft microsoft locked and limited conversation to collaborators Jun 18, 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