ts-type-guards
Version:
Curried TypeScript type guards for primitive types and classes
89 lines • 2.59 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const TYPE_GUARDS_PRIMITIVE = [isBoolean, isNumber, isString, isSymbol, isNull, isUndefined];
function isBoolean(x) {
return typeof x === "boolean";
}
exports.isBoolean = isBoolean;
function isBooleanLike(x) {
return isBoolean(x) || is(Boolean)(x);
}
exports.isBooleanLike = isBooleanLike;
function isNumber(x) {
return typeof x === "number";
}
exports.isNumber = isNumber;
function isNumberLike(x) {
return isNumber(x) || is(Number)(x);
}
exports.isNumberLike = isNumberLike;
function isString(x) {
return typeof x === "string";
}
exports.isString = isString;
function isStringLike(x) {
return isString(x) || is(String)(x);
}
exports.isStringLike = isStringLike;
function isSymbol(x) {
return typeof x === "symbol";
}
exports.isSymbol = isSymbol;
function isNull(x) {
return x === null;
}
exports.isNull = isNull;
function isUndefined(x) {
return x === undefined;
}
exports.isUndefined = isUndefined;
function isNothing(x) {
return x === null || x === undefined;
}
exports.isNothing = isNothing;
function isSomething(x) {
return !isNothing(x);
}
exports.isSomething = isSomething;
function isPrimitive(x) {
return TYPE_GUARDS_PRIMITIVE.some(f => f(x));
}
exports.isPrimitive = isPrimitive;
function isNonPrimitive(x) {
return !isPrimitive(x);
}
exports.isNonPrimitive = isNonPrimitive;
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);
}
function is(type) {
if (isPrimitive(type)) {
return (_) => false;
}
return namedTypeGuard(is, type, (x) => x instanceof type);
}
exports.is = is;
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));
}
exports.isLike = isLike;
//# sourceMappingURL=is.js.map