Skip to content

Commit b324aec

Browse files
committed
feat: Make isEmpty a type guard (#16)
1 parent 0bf3e39 commit b324aec

File tree

1 file changed

+28
-7
lines changed

1 file changed

+28
-7
lines changed

src/utils/is-empty.ts

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,32 @@ import { isArray } from './is-array';
22
import { isString } from './is-string';
33
import { isArguments } from './is-arguments';
44
import { isUndefined } from './is-undefined';
5+
import { isNull } from './is-null';
6+
import { isBoolean } from './is-boolean';
7+
import { isNumber } from './is-number';
58
import { isSet } from './is-set';
9+
import { isObject } from './is-object';
10+
11+
12+
interface IEmptyArguments extends IArguments {
13+
length: 0;
14+
}
15+
16+
interface IEmptyObj {
17+
[s: string]: never;
18+
}
19+
20+
type IEmptyTypes = (
21+
null |
22+
undefined |
23+
boolean |
24+
number |
25+
never[] |
26+
'' |
27+
IEmptyArguments |
28+
Set<never> |
29+
IEmptyObj
30+
);
631

732
/**
833
* Checks if `o` is an empty object. An object is "empty" if it:
@@ -13,8 +38,8 @@ import { isSet } from './is-set';
1338
*
1439
* @returns `true` if `o` is empty
1540
*/
16-
export function isEmpty(o: unknown): boolean {
17-
if (o === null || isUndefined(o)) {
41+
export function isEmpty(o: unknown): o is IEmptyTypes {
42+
if (isNull(o) || isUndefined(o) || isBoolean(o) || isNumber(o)) {
1843
return true;
1944
}
2045
if (isArray(o) || isString(o) || isArguments(o)) {
@@ -23,9 +48,5 @@ export function isEmpty(o: unknown): boolean {
2348
if (isSet(o)) {
2449
return o.size === 0;
2550
}
26-
// Non-object arguments passed into Object.keys are coerced into objects (the only
27-
// exception being undefined or null, which is handled above). Therefore, it's ok to
28-
// assume the input is an object because it will be once passed through. See also:
29-
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys#using_object.keys_on_primitives
30-
return Object.keys(o as object).length === 0;
51+
return isObject(o) && Object.keys(o).length === 0;
3152
}

0 commit comments

Comments
 (0)