property access modifiers in typescript


I recently got Typescript in 50 Lessons and thought I'd share a section.

Typescript allows property access modifiers, aka you can say what can and can't be accessed on a class from The Outside.

class Article {
  public title: string
  private price: number

  constructor(title: string, price: number) {
    this.title = title
    this.price = price
  }
}

const article = new Article('Ulysses', 39)
console.log(article.price) // error

The last line will error with the msg:

Property 'price' is private and only accessible within class 'Article'. (2341)

because of that private prefix in the class declaration. Cool! (here is a titillating github thread on this topic.)

This has been a feature of TS for a while, and now JS has it's own new bizarre imo syntax:

class Article {
  #price: number

  constructor(price: number) {
    this.#price = price
  }
}