diff --git a/src/utils/isDefined.test.ts b/src/utils/isDefined.test.ts new file mode 100644 index 0000000000..5c4af1f830 --- /dev/null +++ b/src/utils/isDefined.test.ts @@ -0,0 +1,14 @@ +import { isDefined } from "./isDefined"; + +describe("isDefined", () => { + it("detects defined values", () => { + expect(isDefined(0)).toBe(true); + expect(isDefined(false)).toBe(true); + expect(isDefined("")).toBe(true); + }); + + it("detects undefined values", () => { + expect(isDefined(undefined)).toBe(false); + expect(isDefined(null)).toBe(false); + }); +}); diff --git a/src/utils/isDefined.ts b/src/utils/isDefined.ts new file mode 100644 index 0000000000..ef5e00ab26 --- /dev/null +++ b/src/utils/isDefined.ts @@ -0,0 +1,3 @@ +export function isDefined(value: T): value is NonNullable { + return value !== undefined && value !== null; +} diff --git a/src/utils/useRequiredContext.ts b/src/utils/useRequiredContext.ts index 63adb9d3b5..aa6e6b9649 100644 --- a/src/utils/useRequiredContext.ts +++ b/src/utils/useRequiredContext.ts @@ -1,5 +1,6 @@ -import { useContext } from "react"; import type { Context } from "react"; +import { useContext } from "react"; +import { isDefined } from "./isDefined"; /** * Passes the call to `useContext` and throw an exception if the resolved value is either `null` or `undefined`. @@ -13,8 +14,8 @@ export default function useRequiredContext( ): NonNullable { const resolved = useContext(context); - if (resolved !== undefined && resolved !== null) { - return resolved as NonNullable; + if (isDefined(resolved)) { + return resolved; } throw new Error(