3
3

More than 3 years have passed since last update.

[Angular] リアクティブフォームのvalueに型を定義する

Last updated at Posted at 2020-04-06

リアクティブフォームのvalueがanyなのをどうにかしたい。
けどそんなに手間をかけたくない。。
そんな時に手軽に型を定義できる方法を発見したので共有します。

目的

https://angular.jp/api/forms/AbstractControl#value
これのanyをどうにかしたい。

簡単な型の定義方法

まずは、FormGroupを拡張した型定義用のclassを用意する。

export class FormGroupTyped<T> extends FormGroup {
  get value(): T {
    return this.value;
  }
}

それを利用して、リアクティブフォームから値を取得する。

// fromの型を定義しておく。
interface Form {
  hoge: string;
}

ngOnInit() {
  const form: FormGroupTyped<Form> = this.formBuilder.group({
    hoge: [''],
  });

  // Formで定義した型となる。  
  form.value.hoge; // => (property) Form.hoge: string
}

これでだけで型を与えることができました!
手軽に導入できるので個人的には気に入っています。
取得した値にTypeGuardをしたりする手間も省けますしね!

参考

3
3
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
3
3