Kim Gysen Kim Gysen - 10 days ago 5
TypeScript Question

Typescript equals

How do I implement equals in Typescript?

I've tried a few methods, both didn't work.

Option 1:

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

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


Results in: Generic type 'GNode' requires 1 type argument(s).

Option 2 would involve casting during runtime, but how to do the casting?:

abstract class GTreeObject{
abstract equals(obj: Object): boolean;
}

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


How to solve reliably?

Answer

According to the TypeScript playground, the only problem is that you forgot to declare the return type of your implementation of equals in GNode:

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

class GNode extends GTreeObject<GNode>{ 
    public equals(obj: GNode) : boolean { 
    // ----------------------^^^^^^^^^^
        return /*implementation*/true;
    } 
}

This complete example works, for instance:

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

Re your comment:

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)?

You'd need to declare the type parameter to GTreeObject as GTree<T>, not just GTree:

class GTree<T> extends GTreeObject<GTree<T>> {
// -------------------------------------^^^
    public equals(obj: GTree<T>) : boolean { 
    // ---------------------^^^
        return /*implementation*/true;
    } 
}
Comments