Answer the question
In order to leave comments, you need to log in
How to use interfaces in function parameters?
Interfaces serve as a guarantee that the class implements all the methods and properties prescribed in it.
It turns out that interfaces are convenient and should be used as a parameter type in functions / methods.
But I'm confused, I have this class that implements the interface cannot be assigned to the interface, here's an example:
typescript
interface INode {
value: any;
left: INode | null;
right: INode | null;
parent: INode | null;
setRight(node: INode): void;
setLeft(node: INode): void;
setParent(node: INode): void;
}
class TreeNode implements INode {
left: this | null = null;
right: this | null = null;
parent: this | null = null;
constructor(public value: any) {}
setLeft(node: this | null): void { // ERROR
this.left = node;
}
setRight(node: this | null): void { // ERROR
this.right = node;
}
setParent(node: this | null): void { // ERROR
this.parent = node;
}
}
Answer the question
In order to leave comments, you need to log in
Because in the interface you have the node parameter of the INode type, and in the class it can be null .
fix like this
setRight(node: INode | null): void;
setLeft(node: INode | null): void;
setParent(node: INode | null): void;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question