首页 > 解决方案 > 有没有办法绕过 ts 2339 来访问类方法或者是否可以在 typescript 中定义类之外的类方法?

问题描述

我打算做的如下

class A {
  constructor() {
    bind(this); 
  }
  hello(){
    this.method1();  // <-- I will get error at this line saying method one does not exist on typeOf A
  }
}
function bind(thisReference) {
  function method1() {
    console.log('in method 1');
  }
  thisReference.method1 = method1.bind(thisReference)
}
var a = new A();
a.hello();

请注意,在我们得到 ts2339 的对象的其他情况下,可以通过定义类型或使用any

我特别希望解决这种情况并因此单独提出问题来解决。在 React 中定义类组件时非常有用,这样我们就可以轻松地在类之外的类上定义新方法。

标签: reactjstypescriptdesign-patternsinterfaceecmascript-next

解决方案


正如@bergi 所说,您需要让它们静态地成为类型的一部分。

我对此熟悉的更常见的模式是使用HoCs 通过props

由于您可以轻松地提供一个函数作为道具,这提供了一种从外部提供一些所需行为的可靠方法。

这种运行时类突变在静态编译语言中表示不是超级“安全”。如果你紧紧地束缚在这种模式下,我不确定你是否真的可以避免as any这种情况。


推荐阅读