如何在Typescript中将通用类的扩展名写为getter

时间:2019-06-02 03:06:56

标签: typescript

所以我学习了如何在打字稿中进行扩展:

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

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

但是如何从中吸气呢?例如:

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

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

这样我就可以调用someArray.lastIndex中的getter吗?

我找到了这个答案,但是代码无法针对泛型类型进行编译,以这种方式编写也很丑陋,但是也许我在打字稿中要求太多:How to extend a typescript class with a get property?

2 个答案:

答案 0 :(得分:0)

这样吧:

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());

答案 1 :(得分:0)

就打字稿接口而言,吸气剂是实施细节。您可以将其声明为普通的只读属性,并将其实现为getter。

interface Array<T> {
  readonly lastIndex: number
}

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

使用ES6速记语法,

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