Generate TypeScript type guards
✓Works with OpenClaudeYou 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
iskeyword (3.7+) viatsc --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
- Parse the target type definition and identify all properties, their types, and optionality
- Determine the guard strategy: simple property checks, discriminated union matching, or nested object validation
- Create a function with
(value: unknown): value is TargetTypesignature for proper type predicate - Implement property existence checks using
typeof,Array.isArray(), or custom validators - For union types, check the discriminator property first to narrow the type efficiently
- Add recursive guard calls for nested object properties
- Return
trueonly when all conditions pass; structure with early returns for readability - 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
Related Code Generation Skills
Other Claude Code skills in the same category — free to download.
Type Generator
Generate TypeScript types from JSON/API responses
Interface from JSON
Generate interfaces from JSON samples
Enum Generator
Generate enums from constant values
Boilerplate Reducer
Generate boilerplate code patterns
Regex Builder
Build and test regular expressions
SQL Generator
Generate SQL queries from natural language
Mock Data Generator
Generate realistic mock data (Faker.js)
Regex Lookahead
Write regex with lookaheads, lookbehinds, and named groups
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.