Add utilty function to check for defined values (#2923)

This commit is contained in:
Jon Koops 2022-07-05 13:01:23 +02:00 committed by GitHub
parent afc04588a5
commit 0929ff03ce
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 21 additions and 3 deletions

View file

@ -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);
});
});

3
src/utils/isDefined.ts Normal file
View file

@ -0,0 +1,3 @@
export function isDefined<T>(value: T): value is NonNullable<T> {
return value !== undefined && value !== null;
}

View file

@ -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<T>(
): NonNullable<T> {
const resolved = useContext(context);
if (resolved !== undefined && resolved !== null) {
return resolved as NonNullable<T>;
if (isDefined(resolved)) {
return resolved;
}
throw new Error(