Typescript Classes 10 exercises
solution

Adding a Getter to a Class in TypeScript

To start, let's create a function named position within the class CanvasNode which would return the x and y properties:


class CanvasNode {
x: number;
y: number;
constructor(position?: { x: number; y: number }) {
this.x = position?.x ?? 0;
this.y = position?.y ?

Loading solution

Transcript

00:00 So, a getter in TypeScript. What you can do is you can say, let's imagine that we had a function called position here. And position took no arguments, but position basically just returned x, which was this dot x, and then y, which was this dot y. Now, what you'd be able to do here is you'd be able to call position every time you wanted the value.

00:20 Currently, position is just a function here, so you would need to actually manually call it for the test to start working. But what if you could just access the property and then intrinsically call the function by doing that? Well, you can by specifying it as a get. So you would say get position,

00:38 and what that means is that position now returns x and y. This means that instead of doing, if I just sort of revert it, and if I say canvasNode.position.x, you notice that it's not available on the position because it's a function that returns the object.

00:55 Whereas if I say that is now a getter, getPosition, now position automatically gets called whenever I access it. So that means I can just access y and x on it directly. This is really cool. And of course, it's not just available to classes as well. You can do getters on normal objects too.

01:14 But on classes, they feel really, really nice because you've just got beautifully type-safe access to all of the properties on this. And of course, I can then access like this.position even in other methods here too, which is super duper cool. So there you go.

01:30 Position is, or rather, getters are super nice in TypeScript because they just let you compose your API into different shapes for different use cases.