gpt4 book ai didi

javascript - typescript 等于

转载 作者:行者123 更新时间:2023-12-01 16:05:02 29 4
gpt4 key购买 nike

如何在 Typescript 中实现 equals?
我尝试了几种方法,都没有奏效。

选项1:

abstract class GTreeObject<T>{ 
abstract equals(obj: T): boolean;
}

class GNode extends GTreeObject<GNode>{
public equals(obj: GNode){
//Implement
}
}

结果:通用类型“GNode”需要 1 个类型参数。

选项 2 将涉及在运行时进行强制转换,但如何进行强制转换?:
abstract class GTreeObject{ 
abstract equals(obj: Object): boolean;
}

class GNode extends GTreeObject{
//How to cast Object to GNode??
public equals(obj: Object){
//Implement
}
}

如何可靠解决?

最佳答案

根据 TypeScript 游乐场,唯一的问题是您忘记声明 equals 实现的返回类型在 GNode :

abstract class GTreeObject<T>{ 
abstract equals(obj: T): boolean;
}

class GNode extends GTreeObject<GNode>{
public equals(obj: GNode) : boolean {
// ----------------------^^^^^^^^^^
return /*implementation*/true;
}
}
这个完整的例子有效,例如:
abstract class GTreeObject<T>{ 
abstract equals(obj: T): boolean;
}

class GNode extends GTreeObject<GNode>{
private value: number;

public constructor(value: number) {
super();
this.value = value;
}
public equals(obj: GNode) : boolean {
return this.value === obj.value;
}
}

let g1 : GNode = new GNode(42);
let g2 : GNode = new GNode(42);
let g3 : GNode = new GNode(27);
console.log(g1.equals(g2)); // true
console.log(g1.equals(g3)); // false

回复您的评论:

Sorry for the hassle. This seems to work for GNode, but when implementing GTree:

class GTree<T> extends GTreeObject<GTree>

this seems to result in an error: Generic type 'GTree' requires 1 type argument(s). Is there a problem using two generic types in the class definition (taking + passing a generic)?


您需要将类型参数声明为 GTreeObjectGTree<T> ,而不仅仅是 GTree :
class GTree<T> extends GTreeObject<GTree<T>> {
// -------------------------------------^^^
public equals(obj: GTree<T>) : boolean {
// ---------------------^^^
return /*implementation*/true;
}
}

关于javascript - typescript 等于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40781948/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com