如何让 TypeScript 发出属性定义,例如:
Object.defineProperties(this, {
view: {
value: view,
enumerable: false,
writable: false,
configurable: false
},
});
最佳答案
您可以在 TypeScript 中使用 get
和 set
,它们会编译成 Object.defineProperties
。
这是 ECMAScript 5 的一项功能,因此如果您的目标是 ES3(编译器的默认设置),则不能使用它。如果您愿意以 ES5 为目标,请将 --target ES5
添加到您的命令中。
typescript :
class MyClass {
private view;
get View() { return this.view; }
set View(value) { this.view = value }
}
编译为:
var MyClass = (function () {
function MyClass() { }
Object.defineProperty(MyClass.prototype, "View", {
get: function () {
return this.view;
},
set: function (value) {
this.view = value;
},
enumerable: true,
configurable: true
});
return MyClass;
})();
但是如果您想要完全控制可枚举和可配置的设置 - 您仍然可以使用原始的 Object.defineProperties
代码。
关于typescript - 如何在 TypeScript 中自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12696250/