'How to access class parameter in anonymous object in Typescript?

How can I access class members during the creation of an anonymous object?

class foo {
   private working = 'hello';
   private notWorking = 'world';

   public method() {
      new DoSomethingClass(working, {
         ...,
         this.notWorking //this throws an error as this has a different scope now
      });
   }
}


Solution 1:[1]

When passing a config object, make sure it uses the right key:

  new DoSomethingClass(working, {
     theRequiredKey: this.notWorking
  });

Check your library for the key names.

You can still use a shortcut for that you use the same variable name as the key is called, e.g.:

  const theRequiredKey = this.notWorking;
  new DoSomethingClass(working, {
     theRequiredKey, // will create an object with key "theRequiredKey" and its value
  });

This will work as wanted.


Also check if your library has typescript typings available, e.g. via

npm install @types/{library-name}

or create your own typings.

Solution 2:[2]

At runtime there is no way to guarantee that this will have the right scope. A function's scope (proper term is "context") can be customized at call time with bind/call/apply, and if separated from it's object, it loses its original context:

var fn = instance.method;
fn(); // `this` will not be `instance` anymore

Arrow functions allow you to avoid this issue.

public method = () => { ... }

There are other ways like stashing var _this = this, but that's error prone.

Note: arrow class methods are different than regular class methods. Since they need to access instance variables, the typescript-generated function will not be on the prototype, but rather in the class constructor. Each instance will have a separate function instance, instead of all pointing to the same function instance. This might affect performance in hot code paths.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2