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

79
Views
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 answers
Answer question

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 Report

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 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!