-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathguards.ts
52 lines (48 loc) · 1.2 KB
/
guards.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* Returns true if the passed value is a record (object).
*
* @param value
*/
const isRecord = (value: unknown): value is Record<string, unknown> => {
return (
Object.prototype.toString.call(value) === '[object Object]' &&
!Object.is(value, null)
);
};
/**
* Returns true if the passed value is truthy.
*
* @param value
*/
const isTruthy = (value: unknown): boolean => {
if (typeof value === 'string') {
return value !== '';
} else if (typeof value === 'number') {
return value !== 0;
} else if (typeof value === 'boolean') {
return value;
} else if (Array.isArray(value)) {
return value.length > 0;
} else if (isRecord(value)) {
return Object.keys(value).length > 0;
} else {
return false;
}
};
/**
* Returns true if the passed value is null or undefined.
*
* @param value
*/
const isNullOrUndefined = (value: unknown): value is null | undefined => {
return Object.is(value, null) || Object.is(value, undefined);
};
/**
* Returns true if the passed value is a string.
* @param value
* @returns
*/
const isString = (value: unknown): value is string => {
return typeof value === 'string';
};
export { isRecord, isString, isTruthy, isNullOrUndefined };