≪ Today I learned.
RSS購読
    公開日
    タグ
    TypeScript
    著者
    ダーシノ

    TypeScript 4.9に追加されたaccessorについて

    TypeScript 4.9にクラス内自動アクセサが追加された。

    以下のようにクラスのメンバ変数にaccessorをつけることで、gettersetterを自動で生成される。

    class Item {
      accessor name: string
      constructor(name: string) {
        this.name = name
      }
    }

    ↓トランスパイル

    class Item {
      #__name: string
      get name() { this.#__name }
      set name(val) { this.#__name = val }
      constructor(name: string) {
        this.name = name;
      }
    }

    accessorが追加された背景には、TypeScript 5.0で追加されるデコレータに必要になるらしい。

    9.1 Why are auto-accessors needed?

    Auto-accessors are needed by decorators:

    Therefore, we have to use auto-accessors instead of fields whenever a decorator needs more control than it has with fields.

    https://2ality.com/2022/10/javascript-decorators.html#why-are-auto-accessors-needed%3F