英文:
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<FormControl<string>>
would be assignable to FormArray<FormControl<string | null>>
, but instead there is an error (example):
Type 'FormArray<FormControl<string>>' is not assignable to type 'FormArray<FormControl<string | null>>'.
Type 'FormControl<string | null>' is not assignable to type 'FormControl<string>'.
Type 'string | null' is not assignable to type 'string'.
Type 'null' is not assignable to type 'string'.(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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论