The problem is with the typing of the isNullOrUndefined function.
When you use the condition like this
if (value !== null && value !== undefined) {
results.push(value); // value is only T here
it is used as a type constrain. Typescript automatically constrains the type
of value in the if
branch to T
.
But if you use isNullOrUndefined
which returns boolean
, Typescript does not check
the actual implementation of the function - even if you did not specify the return type
explicitly.
if (!isNullOrUndefined(value)) {
results.push(value); // value still is T | null | undefined
}
In order to make it work, you need to type the isNullOrUndefined
as a type contrain as well by specifying the return type as value is null | undefined
isNullOrUndefined = (value: T | null | undefined): value is null | undefined => {
return value === null || value === undefined;
}
Then Typescript will behave the same as with the original version.
if (!isNullOrUndefined(value)) {
results.push(value); // value is T
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…