简体   繁体   English

Typescript为什么类型防护不能对可为null的联合类型的对象的数组按预期方式工作(启用strictNullChecks)

[英]Typescript Why type guard does not work as expected for array of objects of type null-able union(strictNullChecks enabled)

type Field = {test: {more: number} | null}
let fields: Field[] = [{test: {more: 55}}]

Transpiler throws error regardless of the type guard: 无论类型类型为守卫,Transpiler都会引发错误:

if (fields[0].test) {
  fields[0].test.more = 55 // object is possibly null
} 

Here no error: 这里没有错误:

function f(field: Field) {
  if (field.test) field.test.more = 15 // no error
}

Type flow does not keep track of array index access, so it will not remember that you checked the 0 index for null . 类型流不跟踪数组索引访问,因此它不会记住您在0索引中检查了null This was considered but apparently not implemented due to performance considerations You can put the value in a local variable and type guards will work as expected on those: 考虑到这一点,但出于性能方面的考虑 ,显然没有实现。您可以将值放在局部变量中,并且类型防护将在以下方面按预期工作:

type Field = {test: {more: number} | null}
let fields: Field[] = [{test: {more: 55}}]
let d = fields[0];
if (d.test) {
    d.test.more = 55 // object is possibly null
} 

Well, it seems that TypeScript doesn't keep track of nulls in Array indexes, which is a bit strange ... maybe an issue could be opened at GitHub about it. 好吧,似乎TypeScript不能跟踪Array索引中的空值,这有点奇怪...也许可以在GitHub上打开一个有关它的问题。 Anyway, there is a way to prevent that error. 无论如何,有一种方法可以防止该错误。 Once you make that check, you know that test is not null , so you can do: 进行检查后,您知道test不为null ,因此您可以执行以下操作:

if (fields[0].test !== null) {
  fields[0].test!.more = 55 // object is possibly null
}

The ! ! after test will tell the compiler that that variable is defined and different from null or undefined . 经过test后,将告诉编译器该变量已定义,并且不同于nullundefined

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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