[SOLVED] How to access class parameter in anonymous object in Typescript?

Issue

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

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.

Answered By – k0pernikus

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *