Advanced TypeScript type guard generator with sophisticated recursion detection, enhanced enum handling, and comprehensive utility support using guardz 1.12.1 library
npm install guardz-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 runtime library
Quick Start
·
Documentation
·
Examples
·
Features
Report Bug
·
Request Feature
·
Contributing
---
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
- 🔧 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
``bashnpm
npm install guardz-generator -D
$3
Create a configuration file
guardz.generator.config.ts:`typescript
export default {
includes: ['src/*/.ts'],
excludes: [
'node_modules/*/',
'*/.test.ts',
'*/.guardz.ts',
'dist/*/'
]
};
`$3
`bash
Generate for all files in config
npx guardz-generatorGenerate for specific files
npx guardz-generator generate "src/models/*/.ts"Generate for specific type
npx guardz-generator generate "src/*/.ts" -t UserProfile
`$3
`typescript
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
$3
- 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$3
- 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
extends and implements
- Index Signatures: Dynamic object properties with isIndexSignature support
- Empty Object Types: Smart handling of {} types to avoid ESLint no-empty-object-type rule
- Default Type Parameters: Automatic use of default type parameters for generic types$3
- 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
-t flag
- Performance Optimized: Intelligent caching and batch processingExamples
$3
`typescript
// User.ts
interface User {
id: number;
name: string;
email: string;
isActive: boolean;
}
`Generated guard:
`typescript
// 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,
});
};
`$3
`typescript
// ApiResponse.ts
interface ApiResponse {
success: boolean;
data: T;
message?: string;
timestamp: number;
}
`Generated guard:
`typescript
// isApiResponse.guardz.ts
import { isBoolean, isNumber, isString, isUndefinedOr, isType } from 'guardz';export const isApiResponse = (
value: unknown,
isT: (value: unknown) => value is T
): value is ApiResponse => {
return isType(value, {
success: isBoolean,
data: isT,
message: isUndefinedOr(isString),
timestamp: isNumber,
});
};
`$3
`typescript
// Config.ts
interface Config {
settings: {};
metadata: Record;
}
`Generated guard:
`typescript
// 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),
});
};
`$3
`typescript
// GenericType.ts
type BooleanGeneric = {
valid: T;
}interface Test {
defaultCase: BooleanGeneric; // Uses default type parameter
explicitCase: BooleanGeneric; // Uses explicit type parameter
}
`Generated guard:
`typescript
// isTest.guardz.ts
import { isEqualTo, isType } from 'guardz';export const isTest = (value: unknown): value is Test => {
return isType(value, {
defaultCase: isBooleanGeneric(isEqualTo(true)), // Uses default type parameter
explicitCase: isBooleanGeneric(isEqualTo(false)), // Uses explicit type parameter
});
};
`$3
`typescript
// TreeNode.ts
interface TreeNode {
value: number;
children: TreeNode[];
}
`Generated guard:
`typescript
// 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
$3
`typescript
// 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/*/'
],
};
`$3
`bash
npx guardz-generator generate [options] [files...]Options:
-c, --config Path to config file (defaults to guardz.generator.config.ts in project root)
-n, --name Custom name for the type guard function
-t, --type Generate type guard for specific type
--no-post-process Skip running lint, prettier, and tsc on generated files
--includes Glob patterns for files to include
--excludes Glob patterns for files to exclude
--verbose Enable verbose logging
--debug Enable debug logging (creates log file)
-h, --help Display help for command
`$3
Guardz Generator creates guards using all available guardz utilities:
`typescript
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.ts
`Best Practices
$3
`typescript
// guardz.generator.config.ts
export default {
includes: ['src/*/.ts'],
excludes: [
'*/.test.ts',
'*/.guardz.ts',
'node_modules/*/'
],
};
`$3
`typescript
import { isUser } from './models/isUser.guardz';export const validateUser = (data: unknown): User | null => {
return isUser(data) ? data : null;
};
`$3
`typescript
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
-t flag
- Post-Processing: Disable with --no-post-process for faster generationTroubleshooting
$3
1. Missing TypeGuardFnConfig Import
- Ensure
typeGuardCode parameter is passed to buildImportStatements
- Check that recursive types are properly detected2. Import Path Issues
- Verify path aliases in
tsconfig.json`Support the development of Guardz Generator:

- 📖 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
MIT License - see LICENSE for details.