UNPKG

guardz

Version:

A simple and lightweight TypeScript type guard library for runtime type validation.

59 lines (58 loc) 1.95 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getExpectedTypeName = exports.getTypeGuardDisplayName = void 0; const typeGuardMeta_1 = require("./typeGuardMeta"); /** * Returns the display name of a type guard for error messages (e.g. isStringGuard -> isString). */ const getTypeGuardDisplayName = (typeGuardFn) => { const fnName = typeGuardFn.name; if (!fnName) { return 'isType'; } if (fnName.endsWith('Guard')) { return fnName.slice(0, -5); } return fnName; }; exports.getTypeGuardDisplayName = getTypeGuardDisplayName; /** * Get the expected type name from a type guard function * @param typeGuardFn - The type guard function to analyze * @returns The expected type name as a string */ const getExpectedTypeName = (typeGuardFn) => { const wrapperKind = (0, typeGuardMeta_1.getTypeGuardWrapperKind)(typeGuardFn); const innerGuard = (0, typeGuardMeta_1.getTypeGuardInnerGuard)(typeGuardFn); if (wrapperKind && innerGuard) { const innerType = (0, exports.getExpectedTypeName)(innerGuard); if (wrapperKind === 'undefinedOr') { return `${innerType} | undefined`; } if (wrapperKind === 'nullOr') { return `${innerType} | null`; } if (wrapperKind === 'nilOr') { return `${innerType} | null | undefined`; } } const fnName = typeGuardFn.name; if (fnName.startsWith('is')) { let typeName = fnName.slice(2); if (typeName.endsWith('Guard')) { typeName = typeName.slice(0, -5); } if (typeName === 'Type' || typeName === 'Schema') { return 'object'; } if (typeName === 'Array') { return 'Array'; } return typeName.toLowerCase(); } if (!fnName) { return 'unknown'; } return 'unknown'; }; exports.getExpectedTypeName = getExpectedTypeName;