I'm trying to create get and set method for a property:
private _name: string;
Name() {
get:
{
return this._name;
}
set:
{
this._name = ???;
}
}
What's the keyword to set a value?
typescript
I'm trying to create get and set method for a property:
private _name: string;
Name() {
get:
{
return this._name;
}
set:
{
this._name = ???;
}
}
What's the keyword to set a value?
Best Answer
TypeScript uses getter/setter syntax that is like ECMAScript4/ActionScript3.
That will produce this JavaScript, using the ECMAScript 5
Object.defineProperty()
feature.So to use it,
However, in order to use it at all, you must make sure the TypeScript compiler targets ECMAScript5. If you are running the command line compiler, use
--target
flag like this;If you are using Visual Studio, you must edit your project file to add the flag to the configuration for the TypeScriptCompile build tool. You can see that here:
As @DanFromGermany suggests below, if your are simply reading and writing a local property like
foo.bar = true
, then having a setter and getter pair is overkill. You can always add them later if you need to do something, like logging, whenever the property is read or written.Getters can be used to implement readonly properties. Here is an example that also shows how getters interact with readonly and optional types.