Typescript Classes 10 exercises
solution

Add a Setter to a TypeScript Class

The syntax for specifying a setter is very similar to the syntax for specifying a getter. The difference is that we use the set keyword instead of the get keyword.

In this case, the position setter will take in an argument for position, which will be an object with x and y properties:

`

Loading solution

Transcript

00:00 Okay, so the way that we do this is very similar to this syntax. We basically say set position and Then we take in the thing that is required to set the position So we hover over this a set accessor must have exactly one

00:16 Parameter that parameter is going to take in the thing that is being set in this case position And now sets a set of functions are super nice in TypeScript because we don't actually need to give this a type It understands what type it's supposed to be from the thing that the getter

00:33 Returns so nice so this position now We can now say this dot X equals positive X and this dot hash Y equals positive Y Beautiful, this is so so nice and now everything is going to work down the bottom so expect

00:51 Where is it this one here? This is now no longer read-only It's now just a mutable property because it's got a setter attached to it So this kind of getter and setter logic you might be very used to this from other languages But having it in TypeScript and JavaScript because this is not TypeScript only syntax This is also JavaScript syntax, too

01:09 And of course this is also available in object syntax, too but having it in classes Again is really nice because you just get a sort of cleaner API and it feels like it sort of belongs in this kind of Classes mindset too. So there we go getters and setters