I'm looking to create a custom type predicate function that can accurately determine if a number is real and tighten the type as well:
function isRealNumber(input: number | undefined | null): input is number {
return input !== undefined && input !== null && Number.isFinite(input);
}
However, there are scenarios where this approach leads to incorrect types when negated, for instance:
const myNumber: number | null = NaN as any;
if (isRealNumber(myNumber)) {
const b = myNumber; // correct output: b is number
} else {
const b = myNumber; // expected output: `null`, but actual output is `null | number`
}
To address this issue, one workaround involves using multiple conditions in the if statement, which is not 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; // correct output: b is number
} else {
const b = myNumber; // correct output: `null | number`
}
Is there a way in TypeScript to have a single function that can accurately narrow down the type without causing incorrect results when negative?