Understanding Accessors (TS)
Firstly we will understand what are Accessors and why we need them. TypeScript supports getters/setters as a way of intercepting accesses to a member of an object. This gives you a way of having finer-grained control over how a member is accessed on each object.
Let’s convert a simple class to use get
and set
. First, let’s start with an example without getters and setters.
While allowing people to randomly set fullName
directly is pretty handy, we may also want enforce some constraints when fullName
is set.
In this version, we add a setter that checks the length of the newName
to make sure it’s compatible with the max-length of our backing database field. If it isn’t we throw an error notifying client code that something went wrong.
To preserve existing functionality, we also add a simple getter that retrieves fullName
unmodified.
Last updated