Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

105
Views
How to reuse a class method defined in one class which can be used in another class in typescript?

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?

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

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); // []
    }
}

TypeScript Playground Link

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs