How do I get TypeScript to emit property definitions such as:
Object.defineProperties(this, {
view: {
value: view,
enumerable: false,
writable: false,
configurable: false
},
});
To add a property to an object in TypeScript, set the property as optional on the interface you assign to the object using a question mark. You can then add the property at a later point in time without getting a type error.
What does ?: mean in TypeScript? Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .
After you have created an object, you can set or change its properties by calling the property directly with the dot operator (if the object inherits from IDL_Object) or by calling the object's SetProperty method.
You can use get
and set
in TypeScript, which compile into Object.defineProperties
.
This is an ECMAScript 5 feature, so you can't use it if you are targeting ES3 (the default for the compiler). If you are happy to target ES5, add --target ES5
to your command.
TypeScript:
class MyClass {
private view;
get View() { return this.view; }
set View(value) { this.view = value }
}
Compiles to:
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;
})();
But if you want full control of setting enumerable and configurable - you could still use the raw Object.defineProperties
code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With