[英]How to fix problem with null ts type checking?
我有可以为null的类的属性,并且在代码中我正在检查值是否不为null且为数组-向其推送新值,但类型检查器仍认为该值可以为null。 有人可以解释为什么以及如何解决它,谢谢?
class BIT {
head: BIT | null = this;
private value: string;
right: BIT | BIT[] | null = null;
left: BIT | BIT[] | null = null;
somefunction(node: BIT) {
const haveLeft = this.left !== null;
const leftIsBranch = haveLeft && this.left instanceof Array;
if (haveLeft) {
if (leftIsBranch) {
this.left.push(node);
}
}
}
}
UPD:如果我摆脱了布尔变量haveLeft和leftIsBranch,并将其显式添加到if语句中->一切正常。 到底他妈发生了什么?
class BIT {
head: BIT | null = this;
private value: string;
right: BIT | BIT[] | null = null;
left: BIT | BIT[] | null = null; // below you try push: this.left.push(this.value). But your types it's BIT or Array of BIT or null, when 'this.value' is string.
somefunction() {
const haveLeft = this.left !== null;
const leftIsBranch = haveLeft && this.left instanceof Array;
if (haveLeft) {
if (leftIsBranch) {
this.left.push(value); // you forgot to specify 'this': this.left.push(this.value);
}
}
}
}
也代替example: null | BIT
example: null | BIT
可以指定example?: BIT
在TypeScript中,所有类型默认情况下都可以为空:
默认情况下,null和undefined是所有其他类型的子类型。 这意味着您可以将null和undefined分配给数字。
但是,使用
--strictNullChecks
标志时,只能将null和undefined分配给void及其各自的类型。 这有助于避免许多常见错误。 如果要传递字符串或null或未定义,则可以使用联合类型string |。 空| 未定义。 再一次,稍后会更多地讨论联合类型。
[摘自TS docs ]
因此,除非您使用--strictNullChecks
编译器标志,否则添加| null
不需要| null
。
类型检查错误的原因可能是您要检查null
而不是undefined
这是未初始化字段的默认值。 松散的等式( !=
代替!==
)检查应有助于识别未定义的情况:
const haveLeft = this.left != null; // This also excludes `undefined`
请注意以下类型检查。
console.log(typeof null); // object console.log(Array.isArray([])); // true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.