simple-tg
Version:
Simple type guard helpers for TypeScript
46 lines • 1.44 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isIn = exports.isObject = exports.isArray = exports.is = exports.guard = void 0;
function guard(f) {
return f;
}
exports.guard = guard;
/**
* Return a type guard function checking whether a value is the type defined by the matcher
* @param matcher
*/
function is(matcher) {
return typeof matcher === 'function' ?
matcher :
Array.isArray(matcher) ?
guard(x => matcher.some(t => t === typeof x)) :
guard(x => matcher === typeof x);
}
exports.is = is;
/**
* Return a type guard function checking whether a value is an array where each element matches the matcher
* @param matcher
*/
function isArray(matcher) {
return guard(x => Array.isArray(x) && x.every(is(matcher)));
}
exports.isArray = isArray;
/**
* Return a type guard function checking whether a value is an object with the entries defined by the given map of property names to matchers
* @param matchObj
*/
function isObject(matchObj) {
return guard(x => x != null &&
typeof x === 'object' &&
Object.entries(matchObj).every(([k, v]) => is(v)(x[k])));
}
exports.isObject = isObject;
/**
* Return a type guard function checking whether a value equals one of the given values
* @param values
*/
function isIn(values) {
return guard(x => values.includes(x));
}
exports.isIn = isIn;
//# sourceMappingURL=index.js.map