When writing a property setter in Typescript it's not required to include a getter at the same time:
set name(name: string)
{
...
}
However when accessing the corresponding property getter via this.name (which isn't defined) it is not a compile time error and returns the value undefined. I can't understand why and I also can't find any discussion about it.
const theName = this.name; // undefined at runtime, but typed as 'string'
I'm most likely to end up in this situation accidentally and it can waste a lot of time in the rare case where I don't immediately notice.
The 'traditional' way to define a property is like this, so maybe that explains why the decision was made.
Object.defineProperty(Dog.prototype, "name", {
set: function (name) {
},
enumerable: false,
configurable: true
});
Wishful thinking of course but I'd much rather the behavior was to return the original 'raw' value passed in - that would be amazing. And avoid this awful mess :-/
set name(name: string)
{
this._name = name;
doNameStuff(name);
}
get name()
{
return this._name;
}
private _name!: string;