Home > other >  Binding (fn.call) context to a function in an object causes an error
Binding (fn.call) context to a function in an object causes an error

Time:01-27

I have code like this -

const foo = {
  bar(): void {
    window.console.log(this.lorem);
  }
};

foo.bar.call({ lorem: 'ipsum' });

...and TypeScript says this -

Property 'lorem' does not exist on type { bar(): void; }

enter image description here

How may I fix this?

CodePudding user response:

Use a this parameter:

const foo = {
  bar(this: { lorem: string }): void {
    window.console.log(this.lorem);
  }
};
  • Related