フィールド (field)
JavaScriptでインスタンスにフィールドを持たせるには、インスタンス化したオブジェクトのプロパティに値を代入します。
JavaScriptjsclassPerson {}constalice = newPerson ();alice .name = "Alice";
JavaScriptjsclassPerson {}constalice = newPerson ();alice .name = "Alice";
TypeScriptでは、これに加えてフィールドの型注釈を書く必要があります。
TypeScripttsclassPerson {name : string;}constalice = newPerson ();alice .name = "Alice";
TypeScripttsclassPerson {name : string;}constalice = newPerson ();alice .name = "Alice";
TypeScriptは、クラスの宣言に書かれていないフィールドへアクセスした場合、コンパイルエラーになります。
TypeScripttsclassPerson {}constperson = newPerson ();Property 'age' does not exist on type 'Person'.2339Property 'age' does not exist on type 'Person'.console .log (person .); age
TypeScripttsclassPerson {}constperson = newPerson ();Property 'age' does not exist on type 'Person'.2339Property 'age' does not exist on type 'Person'.console .log (person .); age
フィールドは宣言時に型を省略した場合でもコンストラクタで値が代入される場合は、代入する値で型が推論されます。下の例ではコンストラクタでstringの型の値を代入しているためnameはstring型となります。
tsclassPerson {privatename ;constructor(name : string) {this.name =name ;}}
tsclassPerson {privatename ;constructor(name : string) {this.name =name ;}}
初期化なしのフィールドとチェック
TypeScriptのコンパイラーオプションでstrictNullChecksとstrictPropertyInitializationの両方が有効になっている場合、次の例のname: stringの部分はコンパイルエラーとして指摘されます。なぜなら、new Personした直後は、nameがundefinedになるためです。
tsclassPerson {Property 'name' has no initializer and is not definitely assigned in the constructor.2564Property 'name' has no initializer and is not definitely assigned in the constructor.: string; name }constalice = newPerson ();console .log (alice .name );
tsclassPerson {Property 'name' has no initializer and is not definitely assigned in the constructor.2564Property 'name' has no initializer and is not definitely assigned in the constructor.: string; name }constalice = newPerson ();console .log (alice .name );
📄️ strictNullChecks
null・undefinedのチェックを厳しくする
📄️ strictPropertyInitialization
クラスプロパティの初期化を必須にする
この2つのコンパイラーオプションが有効な場合でもチェックを通るように書くには、nameフィールドの型注釈をstring | undefinedのようなユニオン型にする必要があります。
tsclassPerson {name : string | undefined;}constalice = newPerson ();console .log (alice .name );
tsclassPerson {name : string | undefined;}constalice = newPerson ();console .log (alice .name );
コンストラクタを用いたフィールドの初期化
フィールドへの値代入は、コンストラクタを用いて行えます。コンストラクタの中では、thisを用いて値を代入したいフィールドにアクセスします。
TypeScripttsclassPerson {name : string;constructor() {this.name = "Alice";}}
TypeScripttsclassPerson {name : string;constructor() {this.name = "Alice";}}
コンストラクタに引数を持たせれば、フィールドの値を動的に指定できるようにもできます。
TypeScripttsclassPerson {name : string;constructor(personName : string) {this.name =personName ;}}constalice = newPerson ("Alice");
TypeScripttsclassPerson {name : string;constructor(personName : string) {this.name =personName ;}}constalice = newPerson ("Alice");