'Typescript check variable null or undefined
Sorry not sure how to describe my question. Hope the title does not mislead you.
First of all, my issue happens in Angular 11 with strict mode turned on.
Suppose I have an array
let results: T[] = [];
and I have a function as follow and this function does not give any error in Visual Studio Code.
filter = (values: (T | null | undefined)[]): T[] => {
for(let value of values) {
if (value !== null && value !== undefined) {
results.push(value);
}
}
}
However, if I extract the condition to another function, such as
isNullOrUndefined = (value: T | null | undefined): bool => {
return value === null || value === undefined;
}
and then use the function in the above filter function as follow:
filter = (values: (T | null | undefined)[]): T[] => {
for(let value of values) {
if (!isNullOrUndefined(value)) {
results.push(value);
}
}
}
I get an error Argument of type 'Nullable<T>' is not assignable to parameter of type 'T'.
Can anyone please help to have a look? Thank you
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
