TypeScript Fundamentals Getters & Setters
This course has been updated! We now recommend you take the TypeScript Fundamentals, v3 course.
Transcript from the "Getters & Setters" Lesson
[00:00:21] One is used to access state and the other's used to mutate state. But effectively here what we can see, is the getters job is to return the value of a property. The setters job is a function that takes care of whatever it means to set that property. And from the outside world we don't know the difference between this and a value based property.
[00:00:44] There are ways to figure it out, right? You can get into the world of object property descriptors and things like that. But the way you use it conventionally, as you see down here, is I can just call name.full and use assignment and we're just gonna end up, that will have the consequence of invoking the getter or the setter.
[00:01:07] So in this case, you can see I've created a derived property for full name that is just based on value based properties for first and last name. And when you say, give me your full name, I assemble it together, and return it to you. And when you say, here's your full name, I'm setting it.
[00:01:23] It splits it apart, and updates the value based properties correspondingly. So you can use this in TypeScript, no problem. Really, really powerful idea. Just be sure that you you don't want to surprise your fellow developers. Not many people expect that an assignment operator could have some significant side effects that could cause functions to be invoked, and so on, right?
[00:01:56] This is uncommon enough that it could cause a little bit of confusion. So, something like this, I would say is fair game but, I definitely wouldn't cause like a setter to send a fetch request out and to do all sorts of stuff, that would be really unexpected for anyone else that touches your code.