So I learned how to make extension in typescript:

interface Array<T> {
  lastIndex(): number
}

Array.prototype.lastIndex = function (): number { return this.length - 1 }

But How to make a getter from it ? eg:

interface Array<T> {
  get lastIndex(): number
}

Array.prototype.lastIndex = function (): number { return this.length - 1 }

So that I can just call is as getter in code someArray.lastIndex ?

I found this answer but code wont compile for generic types, also it's quite ugly to write this way but well maybe i ask for too much in typescript : How to extend a typescript class with a get property?

2 Answers

0
Shadab Faiz On

How about like this:

interface Array<T> {
    lastIndex(): number;
    lastValue(): T
}

Array.prototype.lastIndex = function (): number { return this.length - 1 };
Array.prototype.lastValue = function (): any { return this[this.lastIndex()] };

let myArray = ['111,', '43242asd', 'asdasdas'];
console.log(myArray.lastValue());

0
Avin Kavish On

As far as the typescript interface is concerned a getter is an implementation detail. You can declare it as a normal readonly property and implement it as a getter.

interface Array<T> {
  readonly lastIndex: number
}

Object.defineProperty(Array.prototype, "lastIndex", {
  get: function () { return this.length - 1  }
});

Using ES6 shorthand syntax,

Object.defineProperty(Array.prototype, "lastIndex", {
  get() { return this.length - 1  }
});