Skip to content

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

Closed

Description

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'.

Activity

  1. kitsonk commented on Aug 31, 2016

    @kitsonk
    Contributor

    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.

  2. mhegazy commented on Aug 31, 2016

    @mhegazy
    Contributor

    Duplicate of #10422

  3. locked and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions