isNonNullable.ts 558 B

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