Check out these various SO questions discussing Typescript getters/setters: from 2015, Jan 2018, Sept 2018, and more.
Now, the question arises - what is the best approach to define Typescript types for getters/setters in a plain JavaScript object without using the class
syntax? Particularly focusing on understanding typing best practices. Let's take a look at the interface below -
interface Store {
activeEvent: Date
}
Here are a few criteria for this object -
Avoid using new
for instantiation
Avoid duplicate keys - as seen in the example that doesn't work
const Store: Store = {
activeEvent: new Date(),
get activeEvent() {
return this.activeEvent;
},
}
Avoid leading underscores, which can cause linting issues as per Airbnb's eslint config -
const Store: Store = {
_activeEvent: {},
get activeEvent() {
return this._activeEvent;
},
If possible, include default values but ensure they do not generate errors if the key is dropped, yet still have appropriate behavior when accessed for the first time. This could involve initializing and returning this.activeDate
if it isn't defined initially. However, this blurs the line between a simple getter and a getter/setter method -
get activeDate() {
if(this.activeDate){ return this.activeDate }
const date = new Date()
this.activeDate = date;
return date;
},
Avoid creating redundant keys just to implement getters and setters. It's interesting to note that having the same key for both getter and setter might not produce errors, hinting at potential mistakes in implementation. Any insights on this matter would be greatly appreciated.