Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

236
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda