npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

guardz-generator

v1.12.4

Published

Advanced TypeScript type guard generator with sophisticated recursion detection, enhanced enum handling, and comprehensive utility support using guardz 1.12.1 library

Readme

Guardz Generator

npm version npm downloads GitHub Sponsors


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 -D

Basic 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 UserProfile

Use 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 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

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 -t flag
  • 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 command

Integration 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.ts

Best 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 -t flag
  • Post-Processing: Disable with --no-post-process for faster generation

Troubleshooting

Common Issues

  1. Missing TypeGuardFnConfig Import

    • Ensure typeGuardCode parameter is passed to buildImportStatements
    • Check that recursive types are properly detected
  2. Import Path Issues

    • Verify path aliases in tsconfig.json
    • Check relative path calculations

Support

GitHub Sponsors

Support the development of Guardz Generator:

GitHub Sponsors

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.