[英]Typescript: Why does array includes on an array union type not work?
[英]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都会引发错误:
if (fields[0].test) {
fields[0].test.more = 55 // object is possibly null
}
这里没有错误:
function f(field: Field) {
if (field.test) field.test.more = 15 // no error
}
好吧,似乎TypeScript不能跟踪Array索引中的空值,这有点奇怪...也许可以在GitHub上打开一个有关它的问题。 无论如何,有一种方法可以防止该错误。 进行检查后,您知道test
不为null
,因此您可以执行以下操作:
if (fields[0].test !== null) {
fields[0].test!.more = 55 // object is possibly null
}
!
经过test
后,将告诉编译器该变量已定义,并且不同于null
或undefined
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.