[英]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. 我正在尝试让Angular 5项目中的打字稿
strictNullChecks
工作。
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')
. 我能得到
rememberMe
使用控制this.signinForm.get('rememberMe')
The return of the FormGroup#get
method however, is AbstractControl | null
但是,
FormGroup#get
方法的返回是AbstractControl | null
AbstractControl | null
so typescript doesn't like this.signinForm.get('rememberMe').value
(because it thinks this.signinForm.get('rememberMe')
could be null). AbstractControl | null
因此打字稿不喜欢this.signinForm.get('rememberMe').value
(因为它认为this.signinForm.get('rememberMe')
可能为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
是否可以告诉打字稿, 在这种情况下 ,
this.signinForm.get('rememberMe')
的返回始终是AbstractControl
而不是 AbstractControl | null
AbstractControl | null
? AbstractControl | null
吗?
Use the !
使用
!
operator: 操作员:
this.signinForm.get('rememberMe')!.value
We can force type in TypeScript
by wrapping expression with as [type]
. 我们可以通过将表达式用
as [type]
包装来强制TypeScript
的as [type]
。 In your case it would be (this.signinForm.get('rememberMe') as AbstractControl).value
. 在您的情况下,它将是
(this.signinForm.get('rememberMe') as AbstractControl).value
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.