Skip to content

Instanceof on empty class makes variable in else branch never #10648

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
henkkuli opened this issue Aug 31, 2016 · 2 comments
Closed

Instanceof on empty class makes variable in else branch never #10648

henkkuli opened this issue Aug 31, 2016 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@henkkuli
Copy link

henkkuli commented Aug 31, 2016

TypeScript Version: nightly (2.1.0-dev.20160831)

Code

class Foo {
}
class Bar {
    public baz: string;
}

let a: Foo|Bar = undefined!;

if (a instanceof Foo) {
    // Some code
} else {
    a.baz = "";
}

Expected behavior:
No errors or at least error Property 'baz' does not exist on type 'Foo|Bar'.

Actual behavior:
Error Property 'baz' does not exist on type 'never'.

@kitsonk
Copy link
Contributor

kitsonk commented Aug 31, 2016

I am pretty sure this is covered in a number of other tickets, but don't have the time for the search foo...

Essentially instances of Foo and instances of Bar are structurally the same. TypeScript's type system for various reasons is structurally typed, and because Foo and Bar are of compatible public structures, their instances are assignable to each other. instanceof is the only nominal type checking in ECMAScript, but currently TypeScript still treats it as a structural guard, because of the way its type system works. For TypeScript 2.1 the team continue to look at ways of dealing with instanceof in a nominal way, but allow the rest of the type system to work as designed.

So what is happening is that using instance of, you are eliminate both Foo and Bar from the type and resulting in a never type. In order to work around this current limitation, you would need two classes where their public structure is incompatible for TypeScript to be able to discriminate them.

@mhegazy
Copy link
Contributor

mhegazy commented Aug 31, 2016

Duplicate of #10422

@mhegazy mhegazy added the Duplicate An existing issue was already created label Aug 31, 2016
@mhegazy mhegazy closed this as completed Aug 31, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 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