isNonNullable.ts22 lines · main
1export type Maybe<T> = T | null | undefined
2
3/**
4 * Used to test whether a `Maybe` typed value is `null` or `undefined`.
5 *
6 * When called, the given value's type is narrowed to `NonNullable<T>`.
7 *
8 * ### Example Usage:
9 *
10 * ```ts
11 * const fn = (str: Maybe<string>) => {
12 * if (!isNonNullable(str)) {
13 * // typeof str = null | undefined
14 * // ...
15 * }
16 * // typeof str = string
17 * // ...
18 * }
19 * ```
20 */
21export const isNonNullable = <T extends Maybe<unknown>>(val?: T): val is NonNullable<T> =>
22 typeof val !== `undefined` && val !== null