Alex4answer
Alex4answer

Reputation: 535

What type should the method return?

i try to use TypeScript, but i little bit confused.

i have interface:

interface INode {
  parent: INode | null;
  child: INode | null;
  
  value: any;

  insert(value: any): this; // (or INode or i don't know)
}

and class which implements this interface:

class Node implements INode {
  left: INode | null;
  right: INode | null;
  
  constructor(public value: any, public parent: INode | null = null) {}

  insert(value: any): this { // Type 'Node' is not assignable to type 'this'.
    if(value == this.value) {
      return this;
    }
    return new (<typeof Node>this.constructor)(value, this);// i've find this way in google
  }
}

What type should insert() return ? i've tried made:

insert(value: any): this {
  if(value == this.value) {
    return this;
  }

  return new (<typeof Node>this.constructor)(value, this) as this;
}

but it's looks strange and little bit wrong;

class Node will be Extended and insert() method should return right type;

Upvotes: 0

Views: 49

Answers (1)

Simon
Simon

Reputation: 1312

The insert(value: any) function should return the type INode. Specific implementations can then return Node or a new DerivedNode which are all assignable to INode.

Upvotes: 1

Related Questions