简体   繁体   English

如何告诉Typescript在这种情况下*函数的返回类型永远不会为null

[英]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]包装来强制TypeScriptas [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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM