typing-assets
Version:
Additional typing assets and helpers for better TypeScript experience
72 lines • 2.54 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.generatePredicates = exports.generateAsserter = exports.generateGuard = exports.generateConditionalGuard = exports.isSameType = void 0;
/**
* @description Checks types of borrowed variables list
* @param args List of values
* @returns `boolean` - `true` if types are same, `false` if not
*/
const isSameType = (...args) => {
for (let i = 1; i < args.length; i++) {
if (typeof args[i] === typeof args[i - 1])
continue;
return false;
}
return true;
};
exports.isSameType = isSameType;
/**
* @description Fucntion generator for custom conditional *type guarding*
* @param callback Condition callback function
* @returns `Arrow function`, which returns `checkingVariable` is `T` *(boolean)*
*/
function generateConditionalGuard(callback) {
return (checkingVariable) => {
return callback(checkingVariable);
};
}
exports.generateConditionalGuard = generateConditionalGuard;
/**
*
* @description Function generator for *type guarding*
* @param prop Property to check *(must be string or symbol)*
* @param propPrimitive This property `type` alias primitive in string
* @returns `Arrow function`, which returns `checkingVariable` is `T` *(boolean)*
*/
function generateGuard(prop, propPrimitive) {
return (checkingVariable) => {
return typeof checkingVariable[prop] === propPrimitive;
};
}
exports.generateGuard = generateGuard;
/**
* @param errorMessage Error message `string`
* @param isValid Callback function, that have to return true ro
*
* @returns Type asserter which asserts `checkingVariable` is `T` *(boolean)*
*/
function generateAsserter(errorMessage, isValid) {
return (source, ...args) => {
const state = isValid(source, ...args);
if (!state)
throw new Error(errorMessage);
};
}
exports.generateAsserter = generateAsserter;
function generatePredicates(errorMessage, validationOrProp, propPrimitive) {
if (validationOrProp instanceof Function) {
return {
guard: generateConditionalGuard(validationOrProp),
assert: generateAsserter(errorMessage, validationOrProp)
};
}
else if (propPrimitive) {
const guard = generateGuard(validationOrProp, propPrimitive);
return {
guard,
assert: generateAsserter(errorMessage, guard)
};
}
}
exports.generatePredicates = generatePredicates;
//# sourceMappingURL=predicatesAndTyping.js.map