Small set of functions for value validation and type guarding.
Returns true
if passed value is not null
or undefined
.
Confirms that passed value T
is NonNullable<T>
.
import { isDefined } from 'value-guards';
type Point = null | {
x: number;
y: number;
};
function handlePoint(point: Point): void {
if (isDefined(point)) {
// point is NonNullable<Point>
} else {
// point is null
}
}
Confirms that passed value is function.
import { isFunction } from 'value-guards';
type Initial<T> = T | (() => T);
function handle<T>(initialValue: Initial<T>): void {
if (isFunction(initialValue)) {
// initialValue is () => T
}
}
Confirms that passed value is constructable (newable).
import { isClass } from 'value-guards';
type Initial<T> = { new(): T } | (() => T);
function handle<T>(initialValue: Initial<T>): void {
if (isClass(initialValue)) {
// initialValue may be safely used with new as constructor
}
}
Confirms that passed value is empty array.
import { isEmptyArray } from 'value-guards';
function handle(values: number[]): void {
if (isEmptyArray(values)) {
// values[0] - TS error. Values has no value at index "0"
}
}
Confirms that passed value is array, and it's not empty.
import { isNonEmptyArray } from 'value-guards';
function handle(values: [number?]): void {
if (isNonEmptyArray(values)) {
const value = values[0];
// typeof value is "number"
}
}
Returns true
when passed object is empty.
There are two types of properties checking:
-
"keys"
(default) - Uses internallyObject.keys()
. -
"ownProperties"
- UsesObject.ownPropertyNames()
.
import { isEmptyRecord } from 'value-guards';
isEmptyRecord({}); // true
isEmptyRecord(Object.prototype); // true
isEmptyRecord(Object.prototype, 'ownProperties'); // false
isEmptyRecord(null); // false
isEmptyRecord(undefined); // false
Returns true
is passed object contains properties.
There are two types of properties checking:
-
"keys"
(default) - Uses internallyObject.keys()
. -
"ownProperties"
- UsesObject.ownPropertyNames()
.
import { isNonEmptyRecord } from 'value-guards';
isNonEmptyRecord({}); // false
isNonEmptyRecord(Object.prototype); // false
isNonEmptyRecord(Object.prototype, 'ownProperties'); // true
isNonEmptyRecord(null); // false
isNonEmptyRecord(undefined); // false
Returns true
for "empty" values of HTMLInputElement
.
-
boolean
is always not empty; -
number
is empty when it isNaN
orInfinity
; -
string
empty when it is''
(empty string); -
Date
empty when it isInvalid Date
; - for other types is uses
!
.
MIT