Lesson 17 of 56 · Typescript
Classes – Public, Private, Protected
Duration: 25 minutes
Class Syntax
class Person {
public name: string;
private ssn: string; // hidden from outside
protected birthYear: number; // visible to subclasses
constructor(name: string, ssn: string, birthYear: number) {
this.name = name;
this.ssn = ssn;
this.birthYear = birthYear;
}
public getAge(currentYear: number): number {
return currentYear - this.birthYear;
}
}
Private Fields (# syntax – stage 4)
class Secret {
#token: string;
constructor(token: string) { this.#token = token; }
reveal() { return this.#token; }
}
Access Modifiers Summary
| Modifier | Visibility |
|---|---|
public | Anywhere (default) |
protected | Class and subclasses |
private | Class only |
#private | Class only, enforced at runtime |