Check out a free preview of the full TypeScript Fundamentals course:
The "Getters & Setters" Lesson is part of the full, TypeScript Fundamentals course featured in this preview video. Here's what you'd learn in this lesson:

Mike reviews getters and setters. While a getter is a method that gets the value of a specific property, the setter is a method setting the value of a specific property.

Get Unlimited Access Now

Transcript from the "Getters & Setters" Lesson

>> Mike North: We also have, this has been around in JavaScript for ages, Getters and Setters. An underappreciated, underutilized way that we can have properties that are not value based. But they are based on a getter and a setter. Some people call these, the computer science jargon is an accessor and a mutator.

[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.