Home > Enterprise >  ts narrowing with getter
ts narrowing with getter

Time:10-08

I , am actually look for a cheap solution to allow ts narrowing with a getter or string compare instead of a instanceAB instanceof instanceA to get narrowing.

Is ts have some solution for this?

export class Token {
   type:'TokenContainer'|'TokenPrimitive'|null = null;
   get isContainer(){
      return this.type === 'TokenContainer'
   }
      get isPrimitive(){
       return this.type === 'TokenPrimitive' 
   }
    foo0(){}
}

export class TokenContainer extends Token {
   type:'TokenContainer' = 'TokenContainer';
   foo1(){}
   
}

export class TokenPrimitive extends Token {
    type:'TokenPrimitive' = 'TokenPrimitive'
     foo2(){}
}


let test!:Token;
//           
  • Related