Typescript Classes 10 exercises
Problem

Public and Private Properties in TypeScript

In our CanvasNode class, we have implemented a position getter as our means for accessing node coordinates:


class CanvasNode {
x: number;
y: number;
constructor(position?: { x: number; y: number }) {
this.x = position?.x ?? 0;
this.y = position?.y ?? 0;
}
get p

Loading exercise

Transcript

00:00 Now that we've got our getter for this position here, you might think, okay, now we don't need the outside to be able to access or modify X and Y here. That's really important. So getPosition is kind of like our external API for this and this stuff, the X and Y number,

00:18 are both the internal API. We don't want these to be exposed to the outside. So I've got a test there, which is basically saying, should not be able to access X and Y from the outside, and it's expecting an error when you try to access either X or Y, but currently we're not able to do that.

00:36 Your job is to try to figure out how to make that possible. There is actually two ways of doing this. There is a JavaScript-first way and there is a TypeScript-first way. I would prefer the JavaScript-first way, I think, but I'll forgive you whichever solution you find and good luck if you can find both.