shaky.sh

TypeScript does not have private properties

You might think that TypeScript allows you to have private properties in your classes:

class Foobar {
  private mySecret: string;

  constructor() {
    this.mySecret = "hello";
  }
}

But remember, private properties aren't (yet) a feature of JavaScript. So this will transpile to the following code:

class Foobar {
    constructor() {
        this.mySecret = "hello";
    }
}

Nothing private about that property. It's easily accessible in JavaScript.

It's not even that hard to get around in TypeScript:

const f = new Foobar();
console.log((f as any).mySecret);
// or, if you prefer
console.log((f as unknown as Record<string, unknown>).mySecret);

I can't say I often run into the need for a private field, so I'm not exactly sure what the best practice is these days. But I'd probably reach for a closure:

function createFoobar () {
  const mySecret: string = "hello";

  return {
    getSecretLength() {
      return mySecret.length;
    }
  }
}

It's a fairly old pattern, but it still works great.