reactjs - 有没有办法绕过 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 中定义类组件时非常有用,这样我们就可以轻松地在类之外的类上定义新方法。
解决方案
正如@bergi 所说,您需要让它们静态地成为类型的一部分。
我对此熟悉的更常见的模式是使用HoC
s 通过props
由于您可以轻松地提供一个函数作为道具,这提供了一种从外部提供一些所需行为的可靠方法。
这种运行时类突变在静态编译语言中表示不是超级“安全”。如果你紧紧地束缚在这种模式下,我不确定你是否真的可以避免as any
这种情况。
推荐阅读
- reactjs - react-admin 上 SimpleForm 组件中的自定义布局
- pycharm - 在 PyCharm 中运行 JModelica - 在 PyCharm 解释器之前运行一个 .bat 文件来设置环境
- c# - C# 8 默认接口实现是否允许多重继承
- reactjs - 在多个 Reducer redux 中响应单个 Redux Action
- php - 从 PHP 7.0 升级到 PHP 7.1。致命错误:只能通过引用传递变量 - 使用数组的 $string get_param 命令
- php - 根据 Woocommerce 中的运输方式向客户通知添加回复电子邮件
- javascript - 如何从来自控制台的响应中获取主体并分配给 angular4 中的特定对象
- vhdl - 错误 (10482):VHDL 错误:对象“select_vector”已使用但未声明
- php - 如何查询仅搜索帖子标题?
- python - pipenv 和 rpy2 - 错误:试图猜测 R 的 HOME 但路径中没有命令“R”