0

I've an abstract clas like

class AbsClass {
  type: 'A'|'B'
  constructor(){}
  methodA():void
}

then i have 2 classes thet extends 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')
  }
}

If i have an array of instances that can be of AClass or BClass, in the following code i want that typescript infer the instance type by the property type...

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
  }
}
  • Also https://www.typescriptlang.org/docs/handbook/advanced-types.html. – Jared Smith Dec 26 '20 at 12:02
  • partially yes ... I have to create a function for each class that extends AbsClass, but at this point is easier (inst as AClass).a(). I think that this can be solved with conditional types, but do not understand how – Francesco Bellavita Dec 26 '20 at 12:20
  • 1
    You can write a switch statement on the type property and the compiler should understand what that means. – Jared Smith Dec 26 '20 at 12:37

1 Answers1

0

interface and implements achieve what you want.

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
Akihito KIRISAKI
  • 1,243
  • 6
  • 12