打字稿4:原型方法的临时覆盖

时间:2020-10-27 11:59:19

标签: typescript methods instance delete-operator

下一个代码在打字稿3.3.3上运行(在repl.it上)。每次其他调用时,它都会覆盖或恢复为原型的方法。

class Foo {
  foo () {
    this.foo = function() {
      console.log('instance call')
      delete this.foo // ⟵ Compilation problem with TS4 here
    }
    console.log('prototype call')
  }
}
const f = new Foo()
f.foo()
f.foo()
f.foo()
f.foo()

输出为:

prototype call
instance call
prototype call
instance call

但是此代码无法在打字稿4上编译。删除行会发出““'删除'”运算符的操作数必须是可选的。错误。

有什么方法可以解决特定的编译问题? 可能会有一些小的变化,因为我经常使用这种范例。

1 个答案:

答案 0 :(得分:1)

TypeScript 4.0添加了you may only delete properties that are optional的限制。由于foo的{​​{1}}属性是必需的,因此不允许您Foo使用它。从该实例中删除某个实例(该实例也存在于该原型中)的用例大概没有被考虑,或者被认为不够重要。


通常可以解决此问题的一种方法是使delete方法为可选,如下所示:

foo

但这可能不是,因为您知道class Foo { foo?() { this.foo = function () { console.log('instance call') delete this.foo } console.log('prototype call') } } const f = new Foo() if (f.foo) f.foo() if (f.foo) f.foo() if (f.foo) f.foo() if (f.foo) f.foo() 将始终存在于继承链中。


相反,您只能在foo语句中使用type assertion来告诉编译器将delete视为其this属性是可选的:

foo

Playground link to code