-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathnullish.ts
More file actions
21 lines (18 loc) · 705 Bytes
/
nullish.ts
File metadata and controls
21 lines (18 loc) · 705 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/** Checks if `value` is nullish. Literal types are narrowed accordingly. */
export const nullish = <T>(value: T): value is Nullish<T> =>
value === undefined || value === null;
type Nullish<T> = PickNullish<T> extends never ? Extract<T, undefined | null>
: PickNullish<T>;
type PickNullish<T> =
| (null extends T ? null : never)
| (undefined extends T ? undefined : never);
/**
* Checks if `value` is not nullish. Literal types are narrowed accordingly.
*
* @example
* ```
* const nums = (...values: (number | undefined)[]): number[] => values.filter(notNullish)
* ```
*/
export const notNullish = <T>(value: T | null | undefined): value is T =>
value !== null && value !== undefined;