John
John

Reputation: 10079

How to tell Typescript that *in this instance* a function's return type is never null

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?

Upvotes: 1

Views: 324

Answers (2)

unional
unional

Reputation: 15599

Use the ! operator:

this.signinForm.get('rememberMe')!.value

Upvotes: 4

Patryk Brejdak
Patryk Brejdak

Reputation: 1601

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.

Upvotes: 1

Related Questions