Class members in TypeScript
Access modifiers, parameter properties, and the two kinds of private.
class Session {
#secret = "hidden";
protected runs: number[] = [];
constructor(
public readonly lang: string,
private target = 90,
) {}
record(tpm: number): this {
this.runs.push(tpm);
return this;
}
get stars(): number {
return Math.max(...this.runs) >= this.target ? 3 : 1;
}
reveal(): string {
return this.#secret;
}
}
class Timed extends Session {
get count(): number {
return this.runs.length; // protected: visible here
}
}
const timed = new Timed("ts", 95).record(98) as Timed;
console.log(timed.lang, timed.stars, timed.count, timed.reveal());
How it works
privateis compile-time;#fieldis enforced at run time.- A parameter property declares and assigns in one place.
protectedis visible to subclasses,readonlyto no writer.
Keywords and builtins used here
Mathasclassconstconstructorextendsnumberprivateprotectedpublicreadonlyreturnstringthis
The run, in numbers
- Lines
- 31
- Characters to type
- 557
- Tokens
- 158
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 95 seconds.
Step 2 of 4 in Classes, step 2 of 19 in Classes & patterns.