You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
interfaceIBaseModel{id: string}classBaseClass{model: IBaseModelconstructor(){}setModel(model: IBaseModel){this.model=model}getValueByName(name: string){returnthis.model[name];}}interfaceIDerived1ModelextendsIBaseModel{height: number;}classDerived1extendsBaseClass{// Unsound override!setModel(model: IDerived1Model){super.setModel(model);// Do something with model...}}interfaceIDerived2ModelextendsIBaseModel{width: number;}classDerived2extendsBaseClass{// Unsound override!setModel(model: IDerived2Model){super.setModel(model);// Do something with model...}}constmodel1={id: "0",height: 42};constmodel2={id: "1",width: 24};constobj1=newDerived1();obj1.setModel(model1);constobj2=newDerived2();obj2.setModel(model2);constobjs: BaseClass[]=[obj1,obj2];letvariable: any=null;for(constobjofobjs){if(objinstanceofDerived1){variable=obj.getValueByName("height");// Ok, obj is now of type `Derived1`}elseif(objinstanceofDerived2){variable=obj.getValueByName("width");// Does not compile: Property 'getValueByName' does not exist on type 'never'}console.log("Value is: "+variable);}
TypeScript Version:
2.3.4 and 2.4.1
Code
Expected behavior:
obj
is narrowed toDerived2
.Actual behavior:
obj
is narrowed tonever
.More
See discussion here: https://stackoverflow.com/questions/45381122/typescript-type-narrowed-to-never-with-instanceof-in-an-if-else-statement
When the
setModel
overrides useIBaseModel
as type, it works. However, even though the current code is unsound, I would expect it to compile.The text was updated successfully, but these errors were encountered: