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
Professional TypeScript Type Guard Generator
TypeScript Interfaces · Type Aliases · Enums · Generics · Unions · Intersections
Recursive Types · Cross-file References · NPM Package Types · Complex Patterns
Runtime Validation · Type Safety · Performance Optimized · Production Ready
Transform your TypeScript types into robust runtime validation functions
Built for the [guardz](https://github.com/thiennp/guardz) runtime library
Quick Start
·
Documentation
·
Examples
·
Features
Report Bug
·
Request Feature
·
Contributing
Overview
Guardz Generator is a professional-grade TypeScript type guard generator that transforms your type definitions into robust runtime validation functions. It supports the full spectrum of TypeScript features including complex generics, recursive types, enums, and cross-file dependencies.
Current Version: 1.11.5 - Compatible with guardz 1.11.6
Why Guardz Generator?
- 🔧 Complete TypeScript Support: Every TypeScript feature from primitives to complex recursive types
- ⚡ Performance Optimized: Intelligent caching, batch processing, and selective generation
- 🛡️ Production Ready: Comprehensive error handling, validation, and type safety
- 🎯 Guardz Integration: Full compatibility with the guardz runtime library
- 🔄 Smart Import Resolution: Maintains your project's import structure and path aliases
- 📦 Zero Configuration: Works out of the box with sensible defaults
Quick Start
Installation
npm install guardz-generatorBasic Setup
Create a configuration file guardz.generator.config.ts:
export default {
includes: ['src/**/*.ts'],
excludes: [
'node_modules/**/*',
'**/*.test.ts',
'**/*.guardz.ts',
'dist/**/*'
],
postProcess: true
};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 UserProfileUse Generated Guards
import { isUserProfile } from './models/isUserProfile.guardz';
// Runtime validation
const validateUser = (data: unknown) => {
if (isUserProfile(data)) {
// data is now typed as UserProfile
console.log('Valid user profile:', data.name);
return data;
}
throw new Error('Invalid user profile data');
};Features
Core TypeScript Support
- Interfaces & Type Aliases: Complete support for all interface and type definitions
- Primitive Types:
string,number,boolean,bigint,symbol,null,undefined - Complex Types: Arrays, tuples, unions, intersections, mapped types
- Advanced Features: Generics, conditional types, template literal types
Advanced Capabilities
- Recursive Types: Automatic detection and handling of direct/indirect recursion
- Cross-file References: Types imported from other files with smart resolution
- NPM Package Types: External package types with intelligent fallbacks
- Interface Extensions: Proper inheritance with
extendsandimplements - Index Signatures: Dynamic object properties with
isIndexSignaturesupport
Developer Experience
- Zero Configuration: Works immediately with sensible defaults
- CLI Interface: Simple command-line interface for easy integration
- Post-Processing: Optional formatting, linting, and type checking
- Selective Generation: Generate only needed types with
-tflag - Performance Optimized: Intelligent caching and batch processing
Examples
Basic Interface
// User.ts
interface User {
id: number;
name: string;
email: string;
isActive: boolean;
}Generated guard:
// isUser.guardz.ts
import { isNumber, isString, isBoolean, isType } from 'guardz';
export const isUser = (value: unknown): value is User => {
return isType(value, {
id: isNumber,
name: isString,
email: isString,
isActive: isBoolean,
});
};Complex Generic Type
// ApiResponse.ts
interface ApiResponse<T> {
success: boolean;
data: T;
message?: string;
timestamp: number;
}Generated guard:
// isApiResponse.guardz.ts
import { isBoolean, isNumber, isString, isUndefinedOr, isType } from 'guardz';
export const isApiResponse = <T>(
value: unknown,
isT: (value: unknown) => value is T
): value is ApiResponse<T> => {
return isType(value, {
success: isBoolean,
data: isT,
message: isUndefinedOr(isString),
timestamp: isNumber,
});
};Recursive Type
// TreeNode.ts
interface TreeNode {
value: number;
children: TreeNode[];
}Generated guard:
// isTreeNode.guardz.ts
import { isNumber, isArrayWithEachItem, isType } from 'guardz';
export const isTreeNode = (value: unknown): value is TreeNode => {
return isType(value, {
value: isNumber,
children: isArrayWithEachItem(isTreeNode),
});
};Documentation
Configuration
// guardz.generator.config.ts
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/**/*'
],
// Post-processing options
postProcess: true,
// Custom guard naming
guardNaming: (typeName: string) => `is${typeName}`,
};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 helpIntegration with Guardz Library
Guardz Generator creates guards using all available guardz utilities:
import {
isString, isNumber, isBoolean, isDate,
isAny, isUnknown, isDefined, isNil,
isType, isObject, isArrayWithEachItem,
isExtensionOf, isIntersectionOf, isPartialOf,
isOneOf, isUndefinedOr, isNullOr,
isPositiveNumber, isNonEmptyString,
isFile, isBlob, isFormData,
isIndexSignature, isNumeric, isSchema,
isBooleanLike, isDateLike
} from 'guardz';Project Structure
src/
├── models/
│ ├── User.ts # Your TypeScript interfaces
│ ├── isUser.guardz.ts # Generated type guards
│ ├── ApiResponse.ts
│ └── isApiResponse.guardz.ts
├── types/
├── TreeNode.ts
└── isTreeNode.guardz.tsBest Practices
1. Configuration Management
// guardz.generator.config.ts
export default {
includes: ['src/**/*.ts'],
excludes: [
'**/*.test.ts',
'**/*.guardz.ts',
'node_modules/**/*'
],
};2. Runtime Validation
import { isUser } from './models/isUser.guardz';
export const validateUser = (data: unknown): User | null => {
return isUser(data) ? data : null;
};3. Error Handling
import { isApiResponse } from './models/isApiResponse.guardz';
export const handleApiResponse = (data: unknown) => {
if (isApiResponse(data, isUser)) {
return data.data; // Type-safe access
}
throw new Error('Invalid API response format');
};Performance
- 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.
Development Setup
# Clone the repository
git clone https://github.com/thiennp/guardz-generator.git
cd guardz-generator
# Install dependencies
npm install
# Run tests
npm test
# Build the project
npm run buildSupport
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.