0

When I launch this script I get

Cannot read private member from an object whose class did not declare it

How can I call helloService from a dynamicaly called function (sendToto) without manually injecting it?

export class HelloService {
  sayHello(name: string) {
    console.log('hello', name)
  }
}
export class myClass {
  readonly #helloService: HelloService;

  names: { [index: string]: Array<Function> } = {
    toto: [this.sendToto]
  }

  constructor() {
    this.#helloService = new HelloService();
  }

  send(name: string) {
    // @ts-ignore
    this.names[name][0]('someparams')
    }
  sendToto(params: string) {
    //Cannot read private member from an object whose class did not declare it
    this.#helloService.sayHello(params)
  }
}
(new myClass()).send('toto');
Tib
  • 2,553
  • 1
  • 27
  • 46
  • 1
    `#helloService`? Variable names can't contain `#`, last time I checked... – Cerbrus Oct 25 '21 at 09:33
  • 1
    @Cerbrus It is [ECMAScript Private Fields](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#ecmascript-private-fields) – Ricky Mo Oct 25 '21 at 09:36
  • Oh that's new to me – Cerbrus Oct 25 '21 at 09:38
  • Does this answer your question? [TypeScript "this" scoping issue when called in jquery callback](https://stackoverflow.com/questions/20627138/typescript-this-scoping-issue-when-called-in-jquery-callback) – Cerbrus Oct 25 '21 at 09:40

1 Answers1

2

Method 1:

Replace toto: [this.sendToto] with toto: [this.sendToto.bind(this)]

Method 2:

Make sendToto an arrow function, but has to be declared before names

  sendToto = (params: string) => {
    //Cannot read private member from an object whose class did not declare it
    this.#helloService.sayHello(params)
  }
  
  names: { [index: string]: Array<Function> } = {
    toto: [this.sendToto]
  }
Ricky Mo
  • 6,285
  • 1
  • 14
  • 30