0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[TypeScript] フィールドの初期化子でthisは使える

Posted at

先に結論だけ

フィールド初期化子でthisにアクセスできます。したがって、このコードはトランスパイルできます。

interface A {
   parent:B
}

class B {
    readonly instanceA : A = {parent:this}
}

PlayGround

はじめに

この記事は、TypeScriptにおけるフィールドの初期化子とthisの関係を記録、共有するためのものです。

想定する読者

  • JavaScriptおよびTypeScriptの開発経験がある

対象とする環境

  • TypeScript 5.0.4

フィールドの初期化子とは

フィールドの初期化子とは、クラスのメンバー変数に初期値を与える演算子です。

フィールド初期化子はJavaScriptコードにどう変換されるか

フィールドの初期化子は、JavaScriptに変換するとコンストラクター内での処理になります。記事冒頭のサンプルコードをトランスパイルすると、以下のようになります。

"use strict";
class B {
    constructor() {
        this.instanceA = { parent: this };
    }
}

したがってフィールド初期化子の中のthisはクラスBのインスタンスになります。

フィールドの初期化子を使うと、コンストラクターの可読性が向上します。また、readonly修飾子を使うことで初期化忘れや再代入といったヒューマンエラーを抑止できます。フィールドの初期化子は積極的に利用しましょう。

以上、ありがとうございました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?