So, I'm new to Typescript, and recently started learning from documentation. I was looking at its documentation and there were no signs of reusing method from other class. Class A file
export class A{
... constuctor(){
const queue = this.createQueue()
}
createQueue(){
console.log("Has access to this", +this);
}
}
And there is a class B with exact same definations and uses the same method. How do I make this reusable so that, both of them call with "this"? One solution I thought of is to create a seperate helper Class that could I use, but I'm not sure how to do that. Any thoughts?
In this case, inheritance would probably be your best bet. This basically means that you can extend upon another class and include all of the other one's properties/getters/setters/methods.
// we denote this class as abstract because it must be extended and cannot be directly initialized, i.e. new BaseFoo()
abstract class BaseFoo<T> { // `T` is the item type within the queue
queue: T[];
constructor() {
this.queue = this.createQueue();
}
createQueue() {
// can access `this`
return [];
}
}
class FooA extends BaseFoo<number> {
constructor() {
super(); // runs child class's constructor
console.log(this.queue); // []
}
}
class FooB extends BaseFoo<string> {
constructor() {
super();
console.log(this.queue); // []
}
}