I have property of class that can be null and in code I'm checking if value not null and is array - push new value to it, but type checker still thinks that value can be null. Can somebody explain why and how to fix it, thanks?
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: if I get rid of boolean variables haveLeft and leftIsBranch and explicitly add it to if statement -> everything work just fine. What the heck is going on?
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);
}
}
}
}
Also instead of example: null | BIT
example: null | BIT
you can specify example?: BIT
In TypeScript all types are nullable by default:
By default null and undefined are subtypes of all other types. That means you can assign null and undefined to something like number.
However, when using the
--strictNullChecks
flag, null and undefined are only assignable to void and their respective types. This helps avoid many common errors. In cases where you want to pass in either a string or null or undefined, you can use the union type string | null | undefined. Once again, more on union types later on.
[From TS docs ]
So unless you're using the --strictNullChecks
compiler flag, adding | null
| null
is not necessary.
The cause of your type check error is probably that you're checking against null
but not undefined
- which is the default value of uninitialized fields. A loose equality ( !=
instead of !==
) check should help identifying also undefined cases:
const haveLeft = this.left != null; // This also excludes `undefined`
Note the following type checking.
console.log(typeof null); // object console.log(Array.isArray([])); // true
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.