Add utilty function to check for defined values (#2923)
This commit is contained in:
parent
afc04588a5
commit
0929ff03ce
3 changed files with 21 additions and 3 deletions
14
src/utils/isDefined.test.ts
Normal file
14
src/utils/isDefined.test.ts
Normal 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
3
src/utils/isDefined.ts
Normal file
|
@ -0,0 +1,3 @@
|
|||
export function isDefined<T>(value: T): value is NonNullable<T> {
|
||||
return value !== undefined && value !== null;
|
||||
}
|
|
@ -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(
|
||||
|
|
Loading…
Reference in a new issue