Soft And Hard Privacy Of Properties In JavaScript And TypeScript

[!INFO]-
topic: πŸ¦’ TypeScript
links: What is TypeScript
source: TypeScript course by the native web
tags: #permanent-noteΒ #published

Last Modified: =dateformat(this.file.mtime, "MMM. dd, yyyy - HH:mm")


In TypeScript, you can use keywords like public, private, protected to define the access of properties.

interface Stack {
  isEmpty: () => boolean;
  push: (value: number) => void;
  top: () => number;
  pop: () => number;
}

class InMemoryStack implements Stack {
  private values: number[];

  public constructor () {
    this.values = [];
  }

  public isEmpty (): boolean {
    return this.values.length === 0;
  }

  public push (value: number): void {
    this.values.unshift(value);
  }

  public top (): number {
    return this.values[0];
  }

  public pop (): number {
    const topMostValue = this.values.shift()

    if (topMostValue === undefined) {
      throw new Error('Invalid operation.');
    }

    return topMostValue;
  }
}

const stack = new InMemoryStack();

stack.push(42);
stack.push(23);

// Compiler error, but only as long as we are in the TypeScript world.
// console.log(stack.values);

export {};

However, since TypeScript is compiled into JavaScript, we lose these keywords during compilation.

Since ES2019, JavaScript has a native private construct. You do this, by prepending a # to the property. This works in TypeScript and JavaScript.

interface Stack {
  isEmpty: () => boolean;
  push: (value: number) => void;
  top: () => number;
  pop: () => number;
}

class InMemoryStack implements Stack {
  #values: number[];

  public constructor () {
    this.#values = [];
  }

  public isEmpty (): boolean {
    return this.#values.length === 0;
  }

  public push (value: number): void {
    this.#values.unshift(value);
  }

  public top (): number {
    return this.#values[0];
  }

  public pop (): number {
    const topMostValue = this.#values.shift()

    if (topMostValue === undefined) {
      throw new Error('Invalid operation.');
    }

    return topMostValue;
  }
}

const stack = new InMemoryStack();

stack.push(42);
stack.push(23);

// Works in all environments!
// console.log(stack.#values);

export {};

Unfortunately, JavaScript still doesn't natively support protected.