Package Exports
- guardz-generator
- guardz-generator/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (guardz-generator) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Guardz Generator
A professional TypeScript type guard generator that automatically creates runtime validation functions from your TypeScript interfaces and types using the guardz library.
Current Version: 1.11.3 - Compatible with guardz 1.11.3
Overview
Guardz Generator transforms your TypeScript type definitions into robust runtime type guards, enabling comprehensive runtime validation for your applications. It supports complex TypeScript features including generics, recursive types, enums, and cross-file dependencies.
Key Features
- 🔧 Full TypeScript Support: Interfaces, type aliases, enums, generics, unions, intersections
- 🔄 Recursive Type Handling: Automatic detection and support for direct/indirect recursion
- 📁 Smart Import Resolution: Maintains your project's import structure and path aliases
- ⚡ Performance Optimized: Intelligent caching and batch processing
- 🎯 Guardz Integration: Complete compatibility with guardz 1.11.3 runtime library
- 🔍 Post-Processing: Optional formatting, linting, and type checking
- 🛠️ CLI Interface: Simple command-line interface for easy integration
Installation
npm install guardz-generatorQuick Start
1. Basic Setup
Create a configuration file guardz.generator.config.ts in your project root:
export default {
includes: ['src/**/*.ts'],
excludes: [
'node_modules/**/*',
'**/*.test.ts',
'**/*.guardz.ts',
'dist/**/*'
],
postProcess: true
};2. Generate Type Guards
# Generate for all files in config
npx guardz-generator
# Generate for specific files
npx guardz-generator generate "src/models/**/*.ts"
# Generate for specific type
npx guardz-generator generate "src/**/*.ts" -t StringNumberMap3. Use Generated Guards
import { isStringNumberMap } from './models/isStringNumberMap.guardz';
// Runtime validation
const validateStringNumberMap = (data: unknown) => {
if (isStringNumberMap(data)) {
// data is now typed as { [key: string]: number }
console.log('Valid string-number map');
console.log(Object.keys(data).length, 'entries');
} else {
console.error('Invalid string-number map data');
}
};Configuration
Configuration File Options
export default {
// File patterns to include
includes: ['src/**/*.ts', 'lib/**/*.ts'],
// File patterns to exclude
excludes: [
'node_modules/**/*',
'**/*.test.ts',
'**/*.spec.ts',
'**/*.guardz.ts',
'dist/**/*'
],
};CLI Options
npx guardz-generator generate [options] [files...]
Options:
-c, --config <path> Configuration file path
-n, --name <name> Custom guard function name
-t, --type <type> Generate guard for specific type
--no-post-process Skip formatting and linting
--includes <patterns...> File patterns to include
--excludes <patterns...> File patterns to exclude
-h, --help Display helpSupported TypeScript Features
Core Types
- Interfaces & Type Aliases: Complete support for all interface and type definitions
- Primitive Types:
string,number,boolean,bigint,symbol - Nullable & Optional:
string | null,name?: string - Arrays & Tuples:
string[],[number, string, boolean]
Advanced Types
- Generics:
ApiResponse<T>,PaginatedResponse<T> - Unions & Intersections:
'active' | 'inactive',HasId & HasTimestamps - Recursive Types: Self-referencing interfaces and types
- Enums: String and numeric enums with
isEnum()support
Complex Features
- Interface Extensions:
interface B extends Awith proper inheritance - Index Signatures:
{ [key: string]: unknown }withisIndexSignaturesupport - Intersection Types: Complex types combining index signatures with specific properties
- Cross-file References: Types imported from other files
- NPM Package Types: External package types with smart fallbacks
Integration with Guardz Library
Guardz Generator is fully compatible with guardz 1.11.3 and generates guards using all available utilities:
Core Guards
import {
isString, isNumber, isBoolean, isDate,
isAny, isUnknown, isDefined, isNil,
isType, isObject, isArrayWithEachItem
} from 'guardz';Advanced Guards
import {
isExtensionOf, isIntersectionOf, isPartialOf,
isOneOf, isUndefinedOr, isNullOr,
isPositiveNumber, isNonEmptyString,
isFile, isBlob, isFormData,
isIndexSignature, isNumeric, isSchema,
isBooleanLike, isDateLike
} from 'guardz';Type Aliases
import type { TypeGuardFn, TypeGuardFnConfig } from 'guardz';Project Structure
src/
├── models/
│ ├── StringNumberMap.ts # Your TypeScript interfaces
│ ├── isStringNumberMap.guardz.ts # Generated type guards
│ ├── StringUnionMap.ts
│ └── isStringUnionMap.guardz.ts
├── types/
├── NestedIndexMap.ts
└── isNestedIndexMap.guardz.tsBest Practices
1. Configuration Management
// guardz.generator.config.ts
export default {
includes: ['src/**/*.ts'],
excludes: [
'**/*.test.ts',
'**/*.guardz.ts',
'node_modules/**/*'
],
};2. Import Organization
// Generated guards maintain your import structure
import type { User } from './User';
import { isString, isNumber, isType } from 'guardz';
import { isAddress } from './Address.guardz';3. Runtime Validation
import { isStringNumberMap } from './StringNumberMap.guardz';
export const validateStringNumberMap = (data: unknown): { [key: string]: number } | null => {
return isStringNumberMap(data) ? data : null;
};4. Error Handling
import { isStringUnionMap } from './StringUnionMap.guardz';
export const handleStringUnionMap = (data: unknown) => {
if (isStringUnionMap(data)) {
// Type-safe access to string-keyed map with union values
return Object.entries(data).map(([key, value]) => `${key}: ${value}`);
}
throw new Error('Invalid string-union map format');
};Performance Considerations
- Caching: Import strategies are cached for improved performance
- Batch Processing: Use shared context for multiple file generation
- Selective Generation: Generate only needed types with
-tflag - Post-Processing: Disable with
--no-post-processfor faster generation
Troubleshooting
Common Issues
Missing TypeGuardFnConfig Import
- Ensure
typeGuardCodeparameter is passed tobuildImportStatements - Check that recursive types are properly detected
- Ensure
Import Path Issues
- Verify path aliases in
tsconfig.json - Check relative path calculations
- Verify path aliases in
Post-Processing Errors
- Disable with
--no-post-processflag - Check Prettier/ESLint configuration
- Disable with
Contributing
We welcome contributions! Please see our Contributing Guide for details.
Support
GitHub Sponsors
Support the development of Guardz Generator:
Community Support
- 📖 Documentation: IMPORT_BUILDER.md for advanced usage
- 🐛 Issues: Report bugs on GitHub Issues
- 💬 Discussions: Join community discussions
- ⭐ Star: Show your support by starring the repository
License
MIT License - see LICENSE for details.