Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
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?

about 4 years 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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!