typescript - 该方法应该返回什么类型?
问题描述
我尝试使用 TypeScript,但我有点困惑。
我有界面:
interface INode {
parent: INode | null;
child: INode | null;
value: any;
insert(value: any): this; // (or INode or i don't know)
}
和实现此接口的类:
class Node implements INode {
left: INode | null;
right: INode | null;
constructor(public value: any, public parent: INode | null = null) {}
insert(value: any): this { // Type 'Node' is not assignable to type 'this'.
if(value == this.value) {
return this;
}
return new (<typeof Node>this.constructor)(value, this);// i've find this way in google
}
}
应该insert()
返回什么类型?我试过了:
insert(value: any): this {
if(value == this.value) {
return this;
}
return new (<typeof Node>this.constructor)(value, this) as this;
}
但它看起来很奇怪而且有点不对;
类Node
将被扩展并且insert()
方法应该返回正确的类型;
解决方案
该insert(value: any)
函数应返回类型INode
。然后,特定的实现可以返回Node
或一个新的DerivedNode
,它们都可以分配给INode
.
推荐阅读
- html - 删除 div 之间的垂直空间
- javascript - 我正在尝试使用本地托管的 Django 网络服务器的 HTML 按钮来执行我本地机器上的 python 脚本,但我很难过
- html - 如何在跨度中换行而不破坏单词?
- javascript - 在 Javascript 中模拟私有变量
- reactjs - 无法使仪表图表(使用 Recharts Pie)适合容器
- sql - 如何在 SQL 中到达去年的一周至今和本月至今?
- node.js - mongoose 聚合中无法识别的表达式“$toObjectId”
- javascript - Preact 不会在补液中替换 dom 元素?
- c++ - 打印 char* 指针的完整数据?
- azure-active-directory - 忽略 azure graph API 请求中的多因素身份验证