typestar

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

  1. private is compile-time; #field is enforced at run time.
  2. A parameter property declares and assigns in one place.
  3. protected is visible to subclasses, readonly to no writer.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 4 in Classes, step 2 of 19 in Classes & patterns.

← Previous Next →