为什么在尝试分配看起来兼容的FormArrays时会出现TypeScript错误?

huangapple go评论66阅读模式
英文:

Why is there a typescript error when trying to assign FormArrays that appear to be compatible?

问题

FormArray<FormControl<string>> 期望可分配给 FormArray<FormControl<string | null>>,但实际上出现错误。错误的解释是,string | null 不能分配给 string,这似乎有些令人困惑。

英文:

I would expect from looking at the types that FormArray&lt;FormControl&lt;string&gt;&gt; would be assignable to FormArray&lt;FormControl&lt;string | null&gt;&gt;, but instead there is an error (example):

Type &#39;FormArray&lt;FormControl&lt;string&gt;&gt;&#39; is not assignable to type &#39;FormArray&lt;FormControl&lt;string | null&gt;&gt;&#39;.
  Type &#39;FormControl&lt;string | null&gt;&#39; is not assignable to type &#39;FormControl&lt;string&gt;&#39;.
    Type &#39;string | null&#39; is not assignable to type &#39;string&#39;.
      Type &#39;null&#39; is not assignable to type &#39;string&#39;.(2322)

I'm looking for an explanation for why this is an error. Also, part of the confusion is that the error doesn't make sense, because it seems backward by saying string | null is not assignable to string on line 2 of the error.

答案1

得分: 1

默认情况下,Angular 现在强制使用严格模式。这里定义了一些设置:https://angular.io/guide/strict-mode

对于这个目的来说重要的部分是它启用了 TypeScript 的严格模式。该严格模式的一部分是“严格的空检查”,定义如下:https://www.typescriptlang.org/tsconfig#strictNullChecks

上述引用文档中的一句话是:

> 当 strictNullChecks 为 true 时,null 和 undefined 有它们自己的独特类型,如果你试图在期望具体值的地方使用它们,你将会得到一个类型错误。

这基本上意味着,尽管看起来你应该能将 null 分配给一个字符串,但在 TypeScript 的严格模式下,null 和 undefined 被视为各自独立的类型。

因此,这就是你看到的错误。

英文:

By default, Angular now enforces strict mode. This sets up several things as defined here: https://angular.io/guide/strict-mode

The important part for this purpose is that is enables TypeScript strict mode. Part of that strict mode is "strict null checks" as defined here: https://www.typescriptlang.org/tsconfig#strictNullChecks

A quote from the above references docs:

> When strictNullChecks is true, null and undefined have their own distinct types and you’ll get a type error if you try to use them where a concrete value is expected.

That basically means that, though it seems you should be able to assign null to a string, TypeScript in strict mode treats null and undefined as their own distinct types.

Hence the error you are seeing.

huangapple
  • 本文由 发表于 2023年6月30日 00:25:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76582939.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定