Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. Download free →
CLSkills
Code GenerationintermediateNew

Type Guard Generator

Share

Generate TypeScript type guards

Works with OpenClaude

You are a TypeScript expert specializing in type safety and runtime validation. The user wants to generate TypeScript type guards for custom types and interfaces.

What to check first

  • Verify TypeScript version supports is keyword (3.7+) via tsc --version
  • Inspect the target interface or type definition to understand its shape and required properties
  • Check if discriminated unions are present (they enable simpler type guards)

Steps

  1. Parse the target type definition and identify all properties, their types, and optionality
  2. Determine the guard strategy: simple property checks, discriminated union matching, or nested object validation
  3. Create a function with (value: unknown): value is TargetType signature for proper type predicate
  4. Implement property existence checks using typeof, Array.isArray(), or custom validators
  5. For union types, check the discriminator property first to narrow the type efficiently
  6. Add recursive guard calls for nested object properties
  7. Return true only when all conditions pass; structure with early returns for readability
  8. Export the guard function and test with sample data of both matching and non-matching shapes

Code

// Type guard generator for TypeScript

interface TypeDefinition {
  name: string;
  properties: Record<string, { type: string; optional?: boolean }>;
  discriminator?: string;
}

function generateTypeGuard(definition: TypeDefinition): string {
  const { name, properties, discriminator } = definition;
  const propKeys = Object.keys(properties);
  
  const checks = propKeys.map(key => {
    const prop = properties[key];
    const optional = prop.optional ? '?' : '';
    
    switch (prop.type) {
      case 'string':
        return `typeof value.${key} === 'string'`;
      case 'number':
        return `typeof value.${key} === 'number'`;
      case 'boolean':
        return `typeof value.${key} === 'boolean'`;
      case 'array':
        return `Array.isArray(value.${key})`;
      default:
        return `typeof value.${key} === 'object' && value.${key} !== null`;
    }
  });

  const discriminatorCheck = discriminator
    ? `value.${discriminator} in validValues && `
    : '';

  const allChecks = checks.join(' && ');

  return `function is${name}(value: unknown): value is ${name} {
  if (typeof value !== 'object' || value === null) return false;
  const obj = value as Record<string, unknown>;
  return (
    ${allChecks}
  );
}`;
}

// Implementation example
const userTypeDef: TypeDefinition = {
  name: 'User',
  properties: {
    id: { type: 'number' },
    email: { type: 'string' },
    roles: { type: 'array

Note: this example was truncated in the source. See the GitHub repo for the latest full version.

Common Pitfalls

  • Treating this skill as a one-shot solution — most workflows need iteration and verification
  • Skipping the verification steps — you don't know it worked until you measure
  • Applying this skill without understanding the underlying problem — read the related docs first

When NOT to Use This Skill

  • When a simpler manual approach would take less than 10 minutes
  • On critical production systems without testing in staging first
  • When you don't have permission or authorization to make these changes

How to Verify It Worked

  • Run the verification steps documented above
  • Compare the output against your expected baseline
  • Check logs for any warnings or errors — silent failures are the worst kind

Production Considerations

  • Test in staging before deploying to production
  • Have a rollback plan — every change should be reversible
  • Monitor the affected systems for at least 24 hours after the change

Quick Info

Difficultyintermediate
Version1.0.0
AuthorClaude Skills Hub
codegentype-guardstypescript

Install command:

curl -o ~/.claude/skills/type-guard-generator.md https://claude-skills-hub.vercel.app/skills/code-generation/type-guard-generator.md

Related Code Generation Skills

Other Claude Code skills in the same category — free to download.

Want a Code Generation skill personalized to YOUR project?

This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.