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

80
Vistas
typescript external callback binding within classes

I'm trying to bind properties of a class to a callback inside that class.

Quick example:

// caller
const first = (): void => {
  const testClass = new TestClass();
  testClass.second(() => {
    console.log(this.member) // error TS2532: Object is possibly 'undefined'
  }
}

// TestClass
...
member: string = 'test';

second(cb: () => void) {
 const self = this;
 cb.bind(self)();
}

this seems to be possibly undefined.

How can I access the classes members from an outside callback?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The Arrow Functions are for automatic binding to the current scope and parent objects, so you can't call them with bindings of your callbacks. so here javascript interpreter is trying to find the parent which the callback has been defined before.

// caller
const first = (): void => {
  const testClass = new TestClass();
  testClass.second(function() {
    console.log(this.member)
  }
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

Add a condition before the console log to avoid print undefined objects.

from your example:

// caller
const first = (): void => {
  const testClass = new TestClass();
  testClass.second(() => {
    if (this.member) console.log(this.member)
  }
}

// TestClass
...
member: string = 'test';

second(cb: () => void) {
   const self = this;
    cb.bind(self)();
}

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