【问题标题】:Binding (fn.call) context to a function in an object causes an error将 (fn.call) 上下文绑定到对象中的函数会导致错误
【发布时间】:2023-01-27 04:36:43
【问题描述】:

我有这样的代码 -

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

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

...打字稿这样说-

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

我该如何解决这个问题?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    使用 this 参数:

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

    【讨论】:

      猜你喜欢
      • 2022-11-04
      • 2013-11-29
      • 1970-01-01
      • 2013-09-23
      • 2015-03-06
      • 1970-01-01
      • 2020-03-08
      • 2012-10-17
      • 1970-01-01
      相关资源
      最近更新 更多