简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM