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