1

I'm trying to get typescript strictNullChecks working in an Angular 5 project.

I have a form:

this.signinForm = this.fb.group({
  emailAddress: ['', NGValidators.isEmail()],
  password: ['', Validators.required],
  rememberMe: false,
});

I can get the rememberMe control using this.signinForm.get('rememberMe'). The return of the FormGroup#get method however, is AbstractControl | null so typescript doesn't like this.signinForm.get('rememberMe').value (because it thinks this.signinForm.get('rememberMe') could be null).

Is it possible to tell typescript that, in this instance, the return of this.signinForm.get('rememberMe') is always AbstractControl and not AbstractControl | null?

John
  • 7,008
  • 3
  • 33
  • 62
  • 1
    You can always wrap it with `as any or as AbstractControl` like `(this.signinForm.get('rememberMe') as AbstractControl).value` – Patryk Brejdak Nov 28 '17 at 05:40
  • @Szarik Awesome! That's exactly what I was looking for! If you post that as an answer I'll mark it as correct. – John Nov 28 '17 at 05:43

2 Answers2

4

Use the ! operator:

this.signinForm.get('rememberMe')!.value
unional
  • 10,765
  • 3
  • 26
  • 47
  • I decided to make this the official answer because it provides a better solution to the question asked. Both answers are great / really helpful to know, however (and, obviously, both are valid answers to the question). – John Nov 29 '17 at 14:23
1

We can force type in TypeScript by wrapping expression with as [type]. In your case it would be (this.signinForm.get('rememberMe') as AbstractControl).value.

Patryk Brejdak
  • 1,393
  • 11
  • 22