A
A
alex4answ2020-10-28 11:12:49
typescript
alex4answ, 2020-10-28 11:12:49

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;
  }
}

Error: Property 'setLeft' in type 'TreeNode' is not assignable to the same property in base type 'INode'
etc

Why?
because TreeNode implements the INode interface, I still can't understand

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lynn "Coffee Man", 2020-10-28
@alex4answ

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 question

Ask a Question

731 491 924 answers to any question