【发布时间】:2020-12-26 20:13:51
【问题描述】:
我有一个像这样的抽象类
class AbsClass {
type: 'A'|'B'
constructor(){}
methodA():void
}
然后我有 2 个类扩展 AbsClass:
class AClass extends AbsClass {
constructor(){
super()
this.type = 'A'
}
methodA(){
console.log('my type is A')
}
a(){
console.log('a method')
}
}
class BClass extends AbsClass {
constructor(){
super()
this.type = 'B'
}
b(){
}
methodA(){
console.log('my type is B')
}
}
如果我有一个可以是 AClass 或 BClass 的实例数组,在下面的代码中,我希望打字稿通过属性类型推断实例类型...
const instances:AbsClass[] = [
new AClass(),
new BClass()
]
for(const inst of instances){
if(inst.type == 'A') { //here i want typescript infer the type because only AClass can have 'A' type
inst.a() //AbsClass has not "a" method
}
}
【问题讨论】:
-
部分是的......我必须为每个扩展 AbsClass 的类创建一个函数,但此时更容易(inst as AClass).a()。我认为这可以用条件类型来解决,但不明白如何
-
你可以在 type 属性上写一个 switch 语句,编译器应该明白这意味着什么。
标签: typescript