Deriving Types From Values 15 exercises
explainer

The this Keyword in TypeScript

Like classes and enums, this can also transcend the barrier between the type and runtime worlds.

Let's explore an instance using our CanvasNode class, which includes x and y as numbers:


class CanvasNode {
x: number;
y: number;
constructor(x: number, y: number) {
this.x

Loading explainer

Transcript

00:00 We've talked about how classes and enums too can cross over between the type and the runtime, the value world. And there's one other thing that can do that too. That's this. This can do that. If we look at our CanvasNode class here, we have x number, y number.

00:16 We have a constructor where we have this.x equals x, this.y equals y. And then we have this move function. This move function is slightly different to what we've seen before. Instead of just moving to a place, it actually moves it by a delta. And a delta basically means move this far in this direction.

00:34 So the delta x is a number. Delta y is a number. And we say this.x plus equals the new delta. So x and this.y plus equals y. And then we return this. So this, this is a reference to a value, right? It's the reference to this current CanvasNode.

00:53 And this means that we can, this means, oh good lord. We can actually chain these together. So you can say, okay, CanvasNode, we're going to first move it by 10, 20 and then move it by 30, 40. So we actually end up at 40, 60 because that's the kind of, that's them added together.

01:12 And so by returning this, we can actually kind of chain these together and make a really nice sort of builder pattern style API. And then, of course, we can actually use this as a type in the return type if we want to, which is just amazing.

01:26 We can even do really clever things with this, which we might look at further in the kind of utils folder section. But I wanted to point out that this can be used as a type as well as a value.