[英]How to use Object.defineProperty for getters in Typescript?
我在 JavaScript 中使用了下面給出的實現。
class Base {
installGetters() {
Object.defineProperty(this, 'add', {
get() {
return 5;
}
});
}
}
class New extends Base {
constructor() {
super();
this.installGetters();
}
someAddition() {
return 10 + this.add;
}
}
I have defined the getter property add
in the function of the parent class - Base
and used that property in child class New
after calling the installGetters()
function in the child class constructor. 這適用於 JavaScript,但this.add
在 Typescript 的情況下會引發錯誤。 任何幫助將非常感激。
我這樣做的主要動機是我想將 object 傳遞給installGetters()
以便它可以生成多個 getter,其中 object 鍵是 getter 名稱和從相應的 getter 函數返回的值。
這是在 JavaScript 中工作的,所以我的主要好奇心是這在 TypeScript 中是不可能的,還是我做錯了什么。
盡管這是一個非常奇怪的模式,但我會為您的實際問題提供答案。
TypeScript 不夠聰明,無法根據子類構造函數上調用的方法推斷實際的Base
類型,因此您必須declare
它:
declare readonly add: number;
應用 inheritance 后,我建議使用protected
:
protected 成員僅對聲明它們的 class 的子類可見。
class Base {
protected add!: number;
installGetters() {
this.add = 5;
}
}
與您的問題相關的問題: https://github.com/microsoft/TypeScript/issues/28694
其原因可能是 typescript 不知道您添加的吸氣劑。 沒有打字告訴 typescript 這個吸氣劑存在,typescript 不能神奇地知道你添加了吸氣劑 function 和它的樣子。 您可以在基礎 class 中定義 getter,或者如果這不可能,可能沒有其他方法可以將其轉換為 any。
someAddition() {
return 10 + (this as any).add
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.