【问题标题】:How can I write extension for generic class in typescript as getter如何在 typescript 中为泛型类编写扩展作为 getter
【发布时间】:2019-10-18 02:19:14
【问题描述】:

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

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 中调用 is 作为 getter 吗?

我找到了这个答案,但代码不会为泛型类型编译,这样写也很丑,但也许我在打字稿中要求太多了:How to extend a typescript class with a get property?

【问题讨论】:

标签: typescript


【解决方案1】:

就打字稿接口而言,getter 是一个实现细节。您可以将其声明为普通的只读属性并将其实现为 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  }
});

【讨论】:

  • 这是正确答案。但是,您可能需要注意应避免增加全局变量
  • 这是为什么呢?听起来像你的意见
  • 当然,这是一种观点,但它被广泛持有是有充分理由的。您所要做的就是考虑如果您的依赖项之一执行相同的操作以查看问题发生的位置会发生什么。这样的代码很可能与未来添加的语言本身发生冲突。如果您正在编写一个应用程序,那么这是一个值得商榷的决定,如果您正在编写一个库,那么这绝对是一个糟糕的决定。另外,出于自以为是的原因,我也为您的答案投票。
  • 是的,库作者无权修改全局变量,因为库是供第三方使用的。但作为应用程序代码的作者,我认为在应用程序引导过程中修改全局范围没有问题。你真的认为会有一个名为array.lastIndex 的语言添加除了获取数组的最后一个索引之外还有其他功能吗?添加全局变量是一个明智的执行决策,只有 CTO/lead 才能以影响整个代码库的方式做出。并非每次开发人员都需要实用方法。
  • 这很公平。但我确实认为这对长寿不利。
【解决方案2】:

这样怎么样:

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

【讨论】:

  • 这仍然是函数
猜你喜欢
  • 2010-09-09
  • 2023-01-12
  • 2019-02-12
  • 2021-03-25
  • 1970-01-01
  • 2022-01-21
  • 2018-03-19
  • 1970-01-01
  • 2019-12-05
相关资源
最近更新 更多