Search code examples
javascripttypescripttypeguardsflow-js

How to write a type guard function that tests against null or undefined?


In moving code from flow to js I have the following function:

export function nullOrUndefined(val: mixed): boolean %checks {
    return val === null || val === undefined;
}

Which can be moved to typescript quite easily (changing mixed to unknown)

However it is used like:

const mappedData: Map<string, string> = new Map([["key", "value"]]);
const value: undefined|string = mappedData.get("key"); 
//would be undefined if an invalid key is used
const sentence: string = "The key is: " + (nullOrUndefined(value) ? " not found" : value)
console.log(sentence);

When in flow the %checks makes sure the parser understand the function helps in type narrowing/guarding. How would I do this in typescript?

EDIT: and yes I'm aware this can nearly always be done with the null coalescing operator, though this is from a codebase that is older than that operator.


Solution

  • You can use syntax like this to create a type guard:

    export function nullOrUndefined(a: unknown): a is null | undefined {
      return a == null;
    }
    

    And, by the way, although == is normally discouraged over ===, == with null is a great way to test for both null and undefined at the same time.