有没有一种方法可以针对语言中内置的联合类型对对象进行类似“instanceof”的查询?
我有一个带有联合类型的类型别名,如下所示:
type MyType = Foo | Bar | Thing;
Each of Foo
, Bar
and Thing
继承自Base
class Base { /* ... */ }
class Foo extends Base { /* ... */ }
class Bar extends Base { /* ... */ }
class Thing extends Base { /* ... */ }
某些方法返回一个Base
.
function getBase(): Base { /* ... */ return base; }
理想情况下,我想创建另一个可以返回MyType
打电话后getBase()
function getMyType(): MyType {
var item = getBase();
if (item instanceof MyType)
return item;
else
return null;
}
If MyType
不是类型别名,上面的代码可以工作。但是,由于它是类型别名,因此它似乎不起作用。因此,重申我的问题,语言中是否内置了这种性质的东西?
显然,我想要的可以通过检查每个单独的类的instanceof查询来完成:
function getMyType(): MyType {
var item = getBase();
if (item instanceof Foo || item instanceof Bar || item instanceof Thing)
return item;
else
return null;
}
但这并不理想。如果未来的开发人员想要创建OtherThing
并延伸MyType
还包括这个新课程,然后希望记得更新getMyType()
.
该语言是否内置了一个功能来解决这个问题,或者是否有更好的方法来做到这一点?