ts-type-guards
Version:
Curried TypeScript type guards for primitive types and classes
72 lines • 2.15 kB
JavaScript
const TYPE_GUARDS_PRIMITIVE = [isBoolean, isNumber, isString, isSymbol, isNull, isUndefined];
export function isBoolean(x) {
return typeof x === "boolean";
}
export function isBooleanLike(x) {
return isBoolean(x) || is(Boolean)(x);
}
export function isNumber(x) {
return typeof x === "number";
}
export function isNumberLike(x) {
return isNumber(x) || is(Number)(x);
}
export function isString(x) {
return typeof x === "string";
}
export function isStringLike(x) {
return isString(x) || is(String)(x);
}
export function isSymbol(x) {
return typeof x === "symbol";
}
export function isNull(x) {
return x === null;
}
export function isUndefined(x) {
return x === undefined;
}
export function isNothing(x) {
return x === null || x === undefined;
}
export function isSomething(x) {
return !isNothing(x);
}
export function isPrimitive(x) {
return TYPE_GUARDS_PRIMITIVE.some(f => f(x));
}
export function isNonPrimitive(x) {
return !isPrimitive(x);
}
function namedFunction(name, fun) {
return Object.defineProperty(fun, "name", { value: name, writable: false });
}
function namedTypeGuard(creator, type, typeGuard) {
return namedFunction(`${creator.name}(${type.name})`, typeGuard);
}
export function is(type) {
if (isPrimitive(type)) {
return (_) => false;
}
return namedTypeGuard(is, type, (x) => x instanceof type);
}
export function isLike(reference) {
for (const f of TYPE_GUARDS_PRIMITIVE) {
if (f(reference)) {
return (x) => f(x);
}
}
if (is(Array)(reference)) {
return (x) => is(Array)(x) && (reference.length > 0 ? x.every(isLike(reference[0])) : true);
}
if (reference.constructor === Object) {
return (x) => (isSomething(x)
&&
Object.keys(reference).every(k => isLike(reference[k])(x[k])));
}
if (reference.constructor instanceof Function) {
return is(reference.constructor);
}
throw new TypeError(isLike.name + ` cannot use this object as reference because it has no constructor: ` + JSON.stringify(reference));
}
//# sourceMappingURL=is.js.map