Dev Helpers
← Back

Encapsulate a private field

Encapsulate a private field using TypeScript.

Open this example in the interactive library

Source code

interface Named {
  name: string;
}
console.log(
  (() => {
    class Counter {
      private n = 0;
      next() {
        return ++this.n;
      }
    }
    return new Counter().next();
  })(),
);

Sample output

1