【问题标题】:typescript recognize type of class instance based on instance property [duplicate]打字稿根据实例属性识别类实例的类型
【发布时间】: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


【解决方案1】:

interface 和 implements 实现你想要的。

interface T {
  t: U
}
type U = 'a' | 'b'

class A implements T {
  t: U = 'a' 
}

class B implements T {
  t: U = 'b' 
}

function isA(x: A | B): boolean {
  return x.t === 'a'
}

console.log(isA(new A())) // true
console.log(isA(new B())) // false

【讨论】:

    猜你喜欢
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多