TL ; DR:
TypeScript has the
privatekeyword: only code inside the class can use that field.class Dog { private name: string; constructor(name: string) { this.name = name; } getName(): string { return this.name; } }
Outside the class,
rex.nameis a compile error. The check exists only at compile time: the compiled JavaScript has noprivate.JavaScript's own
#namefields (ES2022) are truly private at run time, and TypeScript supports them too.
Full lesson:
For decades, JavaScript classes had no real privacy — programmers used a leading underscore (_name) as a convention. TypeScript adds the private keyword, and ES2022 added true private fields with the # prefix.
How private works
- You declare the field at the top of the class body with its type:
private name: string; - You access it as
this.nameinside the class's methods. - Trying to access it from outside is a compile error (the compiler reports it), not a run-time error.
Your task
The Dog class declares private name and the constructor stores into it. Add a getName() method, with a string return type, that returns this.name.
Dog's name: RexFree plan: 30 tutor messages. PRO is unlimited.
