ts-rtcheck
Version:
A Typescript runtime checker
110 lines (109 loc) • 4.03 kB
JavaScript
function errMsg(key, shape, obj, msg) {
return `${msg ? msg + ', ' : ''}${key} is expected to be of type "${Array.isArray(shape[key]) ? shape[key].join(' | ') : shape[key]}", got "${obj[key] === null
? null
: Array.isArray(obj[key])
? 'array'
: typeof obj[key]}"`;
}
export function AssertType(obj, typeShape, msg) {
if (typeof obj !== 'object') {
if (Array.isArray(typeShape)) {
const flag = typeShape.some((type) => {
if (type === 'object' && obj === null) {
return false;
}
return obj != null && typeof obj === type;
});
if (!flag) {
throw new TypeError(`${msg ? msg + ', ' : ''}Input is expected to be of type "${typeShape.join(' | ')}", got "${obj === null ? null : typeof obj}"`);
}
else {
return;
}
}
else {
if (typeof obj !== typeShape) {
throw TypeError(`${msg ? msg + ', ' : ''}Input is expected to be of type "${typeShape}", got "${obj === null ? null : typeof obj}"`);
}
else {
return;
}
}
}
if (Array.isArray(obj) && typeShape === 'array') {
return;
}
if (Array.isArray(obj) && typeShape === 'object') {
throw new TypeError('Input is expected to be of type "object", got "array"');
}
if (Array.isArray(obj) !== Array.isArray(typeShape))
throw new TypeError(`Input is expected to be of type "array", got ${typeof obj}`);
let shape = (Array.isArray(typeShape) ? typeShape[0] : typeShape);
const checkOneObj = (obj) => {
if (typeof shape === 'string') {
obj = { Input: obj };
shape = { Input: shape };
}
for (const key in shape) {
if (Array.isArray(shape[key])) {
const flag = shape[key].some((type) => {
if ((type === 'object' && obj[key] === null) ||
(type === 'object' && Array.isArray(obj[key]))) {
return false;
}
return ((Array.isArray(obj[key]) && type === 'array') ||
(obj != null && typeof obj[key] === type));
});
if (!flag) {
throw new TypeError(errMsg(key, shape, obj, msg));
}
}
else {
if ((shape[key] === 'object' && obj[key] === null) ||
(shape[key] === 'object' && Array.isArray(obj[key])) ||
obj == null ||
typeof obj[key] !== shape[key]) {
if (Array.isArray(obj[key]) && shape[key] === 'array') {
continue;
}
throw new TypeError(errMsg(key, shape, obj, msg));
}
}
}
};
if (Array.isArray(obj)) {
const _obj = obj;
for (obj of _obj) {
checkOneObj(obj);
}
}
else {
checkOneObj(obj);
}
}
export function isType(obj, typeShape) {
try {
AssertType(obj, typeShape);
}
catch (_a) {
return false;
}
return true;
}
export function isObject(obj) {
return obj != null && typeof obj === 'object';
}
export function AssertObject(obj, msg) {
if (!(obj != null && typeof obj === 'object'))
throw new TypeError(`${msg ? msg + ', ' : ''}Input is expected to be an object, got "${obj === null ? null : typeof obj}"`);
}
export function AssertExist(obj, msg) {
if (obj == null)
throw new TypeError(`${msg ? msg + ', ' : ''}Input doesn't exist`);
}
export function isExist(obj) {
return obj != null;
}
export function forceCast(obj, cb) {
cb === null || cb === void 0 ? void 0 : cb(obj);
}