セッターとゲッター (set, get)
プロパティへのインターセプター(参照・代入・監視などの意味)としGetter/Setterがあります。
記述方法のサンプルは次のようになります。
ts
class Human {private _name: string;// Getter宣言get name(): string {return this._name;}// Setter宣言set name(name: string) {this._name = name;}}const human = new Human();// Setterを利用human.name = `田中太郎`;// Getterを利用console.log(human.name); // 田中太郎
ts
class Human {private _name: string;// Getter宣言get name(): string {return this._name;}// Setter宣言set name(name: string) {this._name = name;}}const human = new Human();// Setterを利用human.name = `田中太郎`;// Getterを利用console.log(human.name); // 田中太郎
メソッドと違い、getter/setterを呼ぶ場合は()
は不要です。
ts
// Getterconsole .log (human .name ); // 正しいGetterの使用方法This expression is not callable because it is a 'get' accessor. Did you mean to use it without '()'? Type 'String' has no call signatures.6234This expression is not callable because it is a 'get' accessor. Did you mean to use it without '()'? Type 'String' has no call signatures.console .log (human .()); // エラー :human.name is not a function name // Setterhuman .name = "田中太郎"; // 正しいSetterの使用方法This expression is not callable. Type 'String' has no call signatures.2349This expression is not callable. Type 'String' has no call signatures.human .("田中太郎"); name
ts
// Getterconsole .log (human .name ); // 正しいGetterの使用方法This expression is not callable because it is a 'get' accessor. Did you mean to use it without '()'? Type 'String' has no call signatures.6234This expression is not callable because it is a 'get' accessor. Did you mean to use it without '()'? Type 'String' has no call signatures.console .log (human .()); // エラー :human.name is not a function name // Setterhuman .name = "田中太郎"; // 正しいSetterの使用方法This expression is not callable. Type 'String' has no call signatures.2349This expression is not callable. Type 'String' has no call signatures.human .("田中太郎"); name
Getter
Getterの記述方法を日本語で表すと次のようになります。
ts
get 名前(): 型 {必要ならば処理();return 戻り値;}
ts
get 名前(): 型 {必要ならば処理();return 戻り値;}
Getterに引数を指定することはできません。また戻り値を必ず指定する必要があります。
Setter
Setterの記述方法を日本語で表すと次のようになります。
ts
set 名前(変数 : 型) {必要ならば処理();保存処理();}
ts
set 名前(変数 : 型) {必要ならば処理();保存処理();}
引数が必ずひとつ必要です。また戻り値を指定することはできません。