guardz
Version:
A simple and lightweight TypeScript type guard library for runtime type validation.
87 lines (86 loc) • 2.76 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isType = isType;
const isNonNullObject_1 = require("./isNonNullObject");
const validationUtils_1 = require("../utils/validationUtils");
const typeGuardMeta_1 = require("../utils/typeGuardMeta");
/**
* Creates a type guard function for validating objects against a schema.
*
* The data type that comes from different sources (like from server side, library, url params) is not always reliable.
* Therefore, we need to use this function to ensure the data type is correct.
*
* @template T - The type to validate
* @param propsTypesToCheck - Object mapping property keys to their type guard functions
* @returns A type guard function that validates the object structure
*
* @example
* ```typescript
* import { isType, isString, isNumber } from 'guardz';
*
* interface User {
* name: string;
* age: number;
* }
*
* const isUser = isType<User>({
* name: isString,
* age: isNumber,
* });
*
* const data: unknown = { name: 'John', age: 30 };
* if (isUser(data)) {
* // TypeScript now knows data is User
* console.log(data.name); // Safe to access
* }
* ```
*
* @example
* ```typescript
* // Nested object validation
* interface Address {
* street: string;
* city: string;
* }
*
* interface User {
* name: string;
* address: Address;
* }
*
* const isAddress = isType<Address>({
* street: isString,
* city: isString,
* });
*
* const isUser = isType<User>({
* name: isString,
* address: isAddress,
* });
* ```
*/
function isType(propsTypesToCheck) {
// Validate input
if (!(0, isNonNullObject_1.isNonNullObject)(propsTypesToCheck, null)) {
throw new TypeError('propsTypesToCheck must be a non-null object');
}
function isTypeGuard(value, config) {
const errorMode = config?.errorMode || 'multi';
if (errorMode === 'multi' || errorMode === 'json') {
const context = {
path: config?.identifier || 'root',
config: config || null
};
const result = (0, validationUtils_1.validateObject)(value, propsTypesToCheck, context);
(0, validationUtils_1.reportValidationResults)(result, config || null);
return result.valid;
}
if (!(0, isNonNullObject_1.isNonNullObject)(value, config))
return false;
return Object.keys(propsTypesToCheck).every(function (key) {
const typeGuardFn = propsTypesToCheck[key];
return typeGuardFn(value[key], config ? { ...config, identifier: `${config.identifier}.${key}` } : null);
});
}
return (0, typeGuardMeta_1.attachTypeGuardMeta)(isTypeGuard, { schema: propsTypesToCheck });
}