I'm interested in building a type predicate function like this, which will return true when the number is a real number and simultaneously make the type stricter:
function isRealNumber(input: number | undefined | null): input is number {
return input !== undefined && input !== null && Number.isFinite(input);
}
However, this produces incorrect types in some circumstances when negated, e.g.:
const myNumber: number | null = NaN as any;
if (isRealNumber(myNumber)) {
const b = myNumber; // b is number, correct
} else {
const b = myNumber; // b is `null`, should be `null | number`
}
This can be worked around using multiple statements in the conditional, but this is less ideal:
function isRealNumber(input: number | undefined | null): boolean {
return input !== undefined && input !== null && Number.isFinite(input);
}
const myNumber: number | null = NaN as any;
if (isRealNumber(myNumber) && myNumber !== null && myNumber !== undefined) {
const b = myNumber; // b is number, correct
} else {
const b = myNumber; // b is `null | number`, correct
}
Is there any way in typescript to have a single function which will correctly narrow the type without also producing incorrect types sometimes when negated?