gpt4 book ai didi

typescript - 如何在 TypeScript 中自定义属性

转载 作者:搜寻专家 更新时间:2023-10-30 20:32:24 24 4
gpt4 key购买 nike

如何让 TypeScript 发出属性定义,例如:

Object.defineProperties(this, {
view: {
value: view,
enumerable: false,
writable: false,
configurable: false
},
});

最佳答案

您可以在 TypeScript 中使用 getset,它们会编译成 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com