Currently, I am working on creating a binary search tree class in Typescript
as part of my learning journey with the language. My aim is to incorporate generics
into this exercise.
In the process of implementing algorithms within the class, I have encountered the need for two fundamental logical operations when dealing with any object: checking equality and determining if one object is greater than another. While it's relatively straightforward to perform these operations with primitive types like number
, using operators such as ===
and >
, things become more complex when working with generic classes.
To address this challenge, I devised a possible "solution" where the user's object must define two specific methods: equals
and greaterThan
. Based on this requirement, I constructed the following code snippet for my tree's node:
class TreeNode<T> {
/* Represents a node in the tree. */
data: T;
left: TreeNode<T> | undefined;
right: TreeNode<T> | undefined;
constructor(data: T) {
this.data = data;
this.left = undefined;
this.right = undefined;
}
equals(obj: TreeNode<T>): boolean {
/* Determines whether an 'equals' function exists in the object. If not found,
attempts to use the === operator for equality comparison. */
if ('equals' in obj.data)
return <boolean>this.data.equals(obj.data);
else
return this.data === obj.data;
}
greaterThan(obj: TreeNode<T>): boolean {
/* Checks if a 'greaterThan' function is present in the object. If absent,
tries to utilize the > operator to compare this.data with obj.data. */
if ('greaterThan' in obj.data)
return <boolean>this.data.greaterThan(obj.data);
else
return this.data > obj.data;
}
}
The intention behind this code snippet is to facilitate comparisons between nodes (with the TreeNode
's functions equals
and greaterThan
being invoked by the BinarySearchTree
class, which isn't included here). When evaluating nodes, the code first checks for the presence of the specified methods in the user's object stored in the data
attribute. If these methods are defined, they are used for comparison; otherwise, assuming the object is a number, relational operators are employed instead.
Confident in my approach, I proceeded to compile the code, only to be met with the following errors:
TS2339: Property 'equals' does not exist on type 'T'.
TS2339: Property 'greaterThan' does not exist on type 'T'.
Despite validating the existence of the required methods, the compiler refuses to proceed with compilation. What steps can I take to resolve this issue?