0

I use the following method, it works but I would like to know if there is a better way.

export abstract class BaseStoreService {

  display() {
    console.log(this.getTypeName());        //     toto
  }

  getTypeName(): any {}
}
export class StoreTodoService extends BaseStoreService {
  getTypeName(): string {
    return 'toto';
  }

so, it works! is there a better way please?

duke666
  • 45
  • 6
  • 2
    Your answer will depend on whether the value would ever need to be dynamically calculated (in which case your technique is probably best), or whether the value is effectively constant (such that subclasses could pass the constant value into the `super()` constructor). – Jeff Bowman Jun 15 '21 at 21:55
  • What's wrong with this way? What are the issues you're concerned about? What does this method not let you do that you would like to do? – Alex Wayne Jun 15 '21 at 21:57
  • 1
    This is the right way, but you have to declare the abstract function in the abstract class: https://stackoverflow.com/questions/13333489/declaring-abstract-method-in-typescript – Guillaume F. Jun 16 '21 at 01:54

2 Answers2

1

This is good way you are using method override. Also you can use variable and send parameter in constructor.

abstract class BaseStoreService {
    DisplayName:string;
    constructor(displayName: string){
        this.DisplayName = displayName;
    }
  display() {
    console.log(this.DisplayName);        //     toto
  }
}
class StoreTodoService extends BaseStoreService {
   constructor(){
       super("toto");
       this.display();
   }
}

See playground

Also see this. Its very useful link for abstract class in Typescript.

Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42
0

here is the final version thanks to your answers :

export abstract class BaseStoreService {

  display() {
    console.log(this.getTypeName());        //     toto
  }

  abstract getTypeName(): any;
}
export class StoreTodoService extends BaseStoreService {
  getTypeName(): string {
    return 'toto';
  }
}
duke666
  • 45
  • 6