Typescript Classes 10 exercises

Receive Arguments in Class Constructors

In order to make a class capable of receiving arguments, you must specify a constructor.

Using the constructor() keyword, you can specify the arguments you want the constructor to accept.

In this case, we'll use opts as an optional argument for an options object that includes properties for `x

Loading solution


00:00 Okay, if you want your class to be able to receive an argument you need to specify a constructor So that's what we're going to do We'll say constructor and then we'll say options for instance We'll say you can pass in X which is number and a Y which is a number and then we can open up that scope

00:16 and we can say this dot X equals ops dot X and let's say or 0 and now it means that it will default to 0 if it passes either a falsy value So 0 or we don't pass anything at all and we'll do the same thing with this dot Y equals ops dot Y

00:35 Or 0 now we get to do a couple of things. We can simplify a little bit of code instead of just saying equals 0 here we can just Kind of like assign them to number and now because it understands that they're definitely assigning them inside the constructor all is well and now

00:53 All of our code down here works beautifully and our new canvas node. We can of course move from the initial location You don't need to pass an option and when you hover over canvas node You can see the type of the thing that it expects There's even a really cool solution here too, which is you now no longer actually need the type annotations on the X and Y

01:11 So you can say X it's just like this X and Y and now X and Y you can see that it Understands that its number again Type script is really clever here Understanding the behavior of what you've put inside your Constructor and understanding that the two types up here are assigned based on that

01:31 So either of these are really really cool you get again You can see how much work TypeScript has put into making classes a really nice kind of thing to use in JavaScript