Typescript Classes 10 exercises

Declaring Methods in TypeScript Classes

There are two main ways to declare methods in classes in TypeScript.

Technique 1

The first way to declare a method uses a syntax similar to how you would declare an object property.

In this case, we'll declare a move() method on the CanvasNode class, which will accept x and y as number

Loading solution


00:00 Okay, the way that we can do this is we can say move and we can declare this kind of like you would declare it on an object. Now this move is going to take an x which is going to be a number and a y which is going to be a number and then we're going to say this dot x equals x and this dot y equals y.

00:18 Beautiful. So now we've just declared basically a method on this canvas node and we can call it and when you hover over a canvas node you'll get access to move x and y here as the members.

00:29 Nice. So this is the first way. There is also a way that you can basically say move here is an actual arrow function instead of being kind of like a method.

00:39 So if we look between the two here, if I just kind of copy one over and I'll just grab this, put it here, you can see that if we have move at the top here this is declaring an arrow function

00:50 which basically means it gets auto bound to the class and this one is kind of like a method where this could technically sort of be kind of messed about with.

00:59 So in general, I mean which one do I prefer? I'm not sure which one I prefer. I generally move to this but I really don't... I generally declare it as an arrow function just because I'm used to declaring arrow functions

01:14 but in most cases you're not going to need to worry too much unless you're handling kind of like legacy React components or things like that. But these are the two main ways that you can declare methods. Both of them are pretty similar. Both of them get access to this and I think you shouldn't need to choose between them all that often.