TypeScript const 和淘汰赛 pureComputed

TypeScript const and knockout pureComputed

我在函数 problem 中引用 this 对象时遇到 编译 问题:

const c = {
  f() {
    console.log("hi");
  },

  problem: ko.pureComputed(() => {
    return this.f();
  }),
};

[ts] 包含箭头函数捕获 'this' 的全局值,隐含类型为 'any'.

如果我将 this 引用为 c:

const c = {
  f() {
    console.log("hi");
  },

  problem: ko.pureComputed(() => {
    return c.f();
  }),
};

[ts] 'c' 隐式具有类型 'any' 因为它没有类型注释并且在其自己的初始化程序中被直接或间接引用。

有人可以帮忙吗?并可能解释?谢谢

根据@ingvar 的评论,我找到了可接受的匿名解决方案 class:

const c = new class {
  f() {
    console.log("hi");
  }

  problem = ko.pureComputed(() => {
    return this.f();
  }, this);
}();

编译成功,句法简洁,语义正确。