When working with typescript, the following code will be typed correctly:
let v: number | null | undefined;
if(v === null || v === undefined) return;
// v is now recognized as a `number`
const v2 = v + 2;
However, if we decide to streamline this process by creating a helper function for the null
and undefined
check, Typescript may raise an issue:
let v: number | null | undefined;
const isNull = (v: number | null | undefined) => v === null || v === undefined;
if(isNull(v)) return;
// In this case, v is typed as `number | null | undefined`
const v2 = v + 2;
Is there a way to pass along the equality check for null
and undefined
when using the helper function isNull
?
One workaround could be to override it with v!
, but this might seem unorthodox and risky as it creates decoupling between the two.