Deriving Types From Values 15 exercises

Using typeof with Classes in TypeScript

One way to solve this challenge would have been to specify the types explicitly:

const positionFromCanvasNode = (node: { x: number; y: number }) => {

However, this is not the most elegant solution.

A better solution would be to use typeof to type the node parameter:

Loading solution


00:00 Okay, so now that we have typeof at our disposal, you might be tempted to say, okay, we're going to say node is typeof canvasNode, like this. But this gets a little bit confusing. Typeof canvasNode, huh? So typeof canvasNode, if we think about it, is actually like a class instantiation.

00:18 So we would have to say const myNode is like new node, and now we're going to get a canvasNode at the end of it. So if you think of typeof canvasNode, it's actually describing the function that creates the class instance, not the class instance itself.

00:37 Another way you can think of this is probably a very sensible solution to this, is just say xNumber and yNumber, and actually TypeScript will let you pass this. This is a perfectly fine solution, but the solution that I was very, because basically like canvasNode here, it has an xNumber on it and it has a yNumber on it,

00:56 and so TypeScript's not going to complain. Nothing about this function is going to fail. It's going to be great. But a cool way that you can kind of like get around this typeof canvasNode thing in TypeScript is actually just to use the name of the class. You can say node is a canvasNode, and now it's going to work absolutely great.

01:14 This is basically the thing that gets instantiated after we create the class. It's the instantiated class that's represented by its name here, and this is kind of cool because sure, we've got typeof available to us, but we can actually just use this as a type as well as a value.

01:33 So this is kind of an instance along with enums. Two enums do this, as we've seen. They kind of cross over between the type and the value world, because like usually if we just had a const example like this, xNumber or x0, y0,

01:49 we couldn't say node is example because this doesn't exist in the type world. Example refers to a value, but it's being used as a type here. Did you mean typeof example? So a really nice little error there too. But classes kind of cross over between the, what's it called, canvasNode.

02:08 They cross over between the value world and the type world, meaning that you can kind of use them in both. A really neat little feature.