TypeScript Only Features 9 exercises
explainer

Parameter Properties in TypeScript

Let's look at parameter properties in TypeScript.

Here we have a CanvasNode class that includes a move function and position getter.


class CanvasNode {
constructor(private x: number, private y: number) {}
move(newX: number, newY: number) {
this.x = newX;
this.y = n

Loading explainer

Transcript

00:00 We're going to start by looking at parameter properties in TypeScript. Here we have a CanvasNode class, which has a move function and a position getter. And it has a constructor, and that constructor has two parameters, has x and y, both of which are numbers.

00:16 And you notice here that private x, it's like there's a little sort of piece of syntax before the x and before the y that's saying private. If I were to change these to public, for instance, that would work too. But if I were to delete them, then something interesting would happen.

00:33 Without the public or private kind of additions to these parameters, then accessing them doesn't seem to make sense. Property x does not exist on CanvasNode. Whereas when I do add public or private, then suddenly it does exist on CanvasNode. Now what these are, these are parameter properties.

00:52 We're basically saying, okay, anything that you pass into CanvasNode, if there's a private or a public before the x and the y, that is going to basically be automatically added to the class using this designation.

01:07 So if I choose public, then that's going to be available on Node.x and Node.y. Whereas if I choose private, then this is going to be not available on Node.x or Node.y. So there we go. This is the first example of something that TypeScript added to the language back in the day

01:24 that's interesting, certainly, but I'm not sure if it would do it right now. You can certainly use these. These will work at runtime and most bundlers that bundle TypeScript will automatically handle this stuff. But it's, yeah, it's definitely not something that would be added today.