Skip to content

Union type is not narrowed by a Symbol property, even though it is correctly narrowed by a "regular" property #28701

Closed
@solymosi

Description

@solymosi

TypeScript Version: 3.3.0-dev.20181128

Search Terms: symbol, property, key, type inference, does not narrow, union type, different behavior of symbol and string keys

Code

const LOADED = Symbol();

class Entity {
  [LOADED]: true = true;
  doStuff() { }
}

class ReferenceToEntity {
  [LOADED]: false = false;
}
 
class SomeClass {
  entity?: Entity | ReferenceToEntity;

  foo() {
    this.entity && this.entity[LOADED] && this.entity.doStuff();
  }    //                                             ^^^^^^^ ERROR!
}

Expected behavior:
Since Entity[LOADED] is of type true and ReferenceToEntity[LOADED] is of type false, I would expect the type of this.entity to be narrowed to just Entity in foo() and the above example to compile, just like it does with string property keys – i.e. this behavior seems to be unique to Symbol properties.

Actual behavior:
Compilation error:

Property 'doStuff' does not exist on type 'Entity | ReferenceToEntity'.
  Property 'doStuff' does not exist on type 'ReferenceToEntity'.

Things that do not change the behavior:

  • marking [LOADED] as readonly
  • explicitly marking LOADED as unique symbol
  • turning [LOADED] into a getter, i.e.
    get [LOADED](): true { return true; }
    
  • disabling strict mode

Things that change the behavior:

  • using string property keys makes it work as intended, i.e. the compiler realizes that if this.entity.loaded is truthy then this.entity˙must be an Entity
  • assigning to entity in foo() just before the doStuff() call also makes it work:
    foo() {
      this.entity = new Entity();
      this.entity && this.entity[LOADED] && this.entity.doStuff();  // NO ERROR
    }
    

Playground Link:
http://www.typescriptlang.org/play/#src=const%20LOADED%20%3D%20Symbol()%3B%0D%0A%0D%0Aclass%20Entity%20%7B%0D%0A%20%20%20%20%5BLOADED%5D%3A%20true%20%3D%20true%3B%0D%0A%20%20%20%20doStuff()%20%7B%20%7D%0D%0A%7D%0D%0A%0D%0Aclass%20ReferenceToEntity%20%7B%0D%0A%20%20%20%20%5BLOADED%5D%3A%20false%20%3D%20false%3B%0D%0A%7D%0D%0A%20%0D%0Aclass%20SomeClass%20%7B%0D%0A%20%20%20%20entity%3F%3A%20Entity%20%7C%20ReferenceToEntity%3B%0D%0A%0D%0A%20%20%20%20foo()%20%7B%0D%0A%20%20%20%20%20%20%20%20this.entity%20%26%26%20this.entity%5BLOADED%5D%20%26%26%20this.entity.doStuff()%3B%0D%0A%20%20%20%20%7D%20%20%20%20%2F%2F%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%5E%5E%5E%5E%5E%5E%5E%20ERROR!%0D%0A%7D

Related Issues:

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