David Thielen
David Thielen

Reputation: 32924

Is there a way to declare a getter in an interface?

I have a class as follows (just showing part):

export class LinkedListNode<t> extends windward.WrObject implements ILinkedListNode<t>{
   public get next():LinkedListNode<t> {
        return this._next === this._list._first ? null : this._next;
    }
}

So in the interface I want to declare next as a method. However, the following does not work:

export interface ILinkedListNode<t> {
       get next() : LinkedListNode<t>;
}

The following does work, but is inaccurate:

export interface ILinkedListNode<t> {
       next : LinkedListNode<t>;
}

Is there a way to declare a getter in an interface? A getter is different than a member variable, for example it is not passed across to a web worker when posting an object.

thanks - dave

Upvotes: 1

Views: 589

Answers (2)

Buzinas
Buzinas

Reputation: 11725

At the moment of writing, there is no way to accomplish what you want.

There is an open issue on TypeScript's Github dated since 2014 July, and that feature will be available as soon as they implement it.

The only way of ~simulate~ what you need, is by doing what David Sherret said in his answer: creating a getter method.

export interface ILinkedListNode<t> {
  getNext(): LinkedListNode<t>;
}

Although, I recommend to only create the property inside your interface now, and changing it to the ~readonly~ or ~get~ version when it be available in the future.

Upvotes: 2

David Sherret
David Sherret

Reputation: 106640

No, although this is possible in other languages like C#, it is not currently possible in TypeScript.

If you want that behaviour, it might be better to make it a method:

export interface ILinkedListNode<t> {
    getNext(): LinkedListNode<t>;
}

Upvotes: 3

Related Questions