Package Exports
- guardz-generator
- guardz-generator/dist/core/generators/type-guard/type-guard-generator.js
- guardz-generator/dist/index.js
- guardz-generator/dist/infrastructure/factories/service-factory.js
- guardz-generator/dist/shared/utils/logging.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.12.1 - Compatible with guardz 1.12.1
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
npm install guardz-generator -D
# yarn
yarn add guardz-generator -D
# pnpm
pnpm add guardz-generator -DBasic Setup
Create a configuration file guardz.generator.config.ts:
export default {
includes: ['src/**/*.ts'],
excludes: [
'node_modules/**/*',
'**/*.test.ts',
'**/*.guardz.ts',
'dist/**/*'
]
};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,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 - Empty Object Types: Smart handling of
{}types to avoid ESLintno-empty-object-typerule - Default Type Parameters: Automatic use of default type parameters for generic types
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,
});
};Empty Object Type
// Config.ts
interface Config {
settings: {};
metadata: Record<string, unknown>;
}Generated guard:
// isConfig.guardz.ts
import { isObjectWithEachItem, isType, isUnknown } from 'guardz';
export const isConfig = (value: unknown): value is Config => {
return isType(value, {
settings: isType({}), // Uses isType({}) instead of isType<{}>({})
metadata: isObjectWithEachItem(isUnknown),
});
};Default Type Parameters
// GenericType.ts
type BooleanGeneric<T extends boolean = true> = {
valid: T;
}
interface Test {
defaultCase: BooleanGeneric; // Uses default type parameter
explicitCase: BooleanGeneric<false>; // Uses explicit type parameter
}Generated guard:
// isTest.guardz.ts
import { isEqualTo, isType } from 'guardz';
export const isTest = (value: unknown): value is Test => {
return isType(value, {
defaultCase: isBooleanGeneric<true>(isEqualTo(true)), // Uses default type parameter
explicitCase: isBooleanGeneric<false>(isEqualTo(false)), // Uses explicit type parameter
});
};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/**/*'
],
};CLI Options
npx guardz-generator generate [options] [files...]
Options:
-c, --config <path> Path to config file (defaults to guardz.generator.config.ts in project root)
-n, --name <name> Custom name for the type guard function
-t, --type <type> Generate type guard for specific type
--no-post-process Skip running lint, prettier, and tsc on generated files
--includes <patterns...> Glob patterns for files to include
--excludes <patterns...> Glob patterns for files to exclude
--verbose Enable verbose logging
--debug Enable debug logging (creates log file)
-h, --help Display help for commandIntegration 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
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.