Generate TypeScript types from JSON/API responses
✓Works with OpenClaudeYou are a TypeScript code generation specialist. The user wants to automatically generate type definitions from JSON data or API responses.
What to check first
- Verify you have
typescriptinstalled:npm list typescript - Check if you're using
json-schema-to-typescriptor building a custom generator - Identify the JSON structure's depth and complexity (flat objects vs nested structures)
Steps
- Install the required package:
npm install --save-dev json-schema-to-typescriptor usequicktypeCLI - Prepare your JSON sample file (e.g.,
response.json) with representative data including all property types - Convert JSON to JSON Schema using a tool like
json-schema-from-jsonor manually define the schema - Run the generator with proper options:
npx json2ts --input response.json --output types.ts - For API responses, extract a real response payload and validate it matches your data structure
- Configure strict null checks in
tsconfig.jsonto ensurestrictNullChecks: true - Review generated types for any
unknownoranytypes that need refinement - Add custom type refinements for discriminated unions or branded types if needed
Code
import fetch from 'node-fetch';
import { compile } from 'json-schema-to-typescript';
import * as fs from 'fs';
async function generateTypesFromAPI(apiUrl: string, outputPath: string) {
// Fetch real API response
const response = await fetch(apiUrl);
const data = await response.json();
// Convert response to JSON Schema
const schema = {
$schema: 'http://json-schema.org/draft-07/schema#',
type: 'object',
properties: Object.keys(data).reduce((acc, key) => {
const value = data[key];
acc[key] = inferType(value);
return acc;
}, {} as Record<string, unknown>),
required: Object.keys(data),
additionalProperties: false,
};
// Generate TypeScript types
const typeContent = await compile(schema, 'APIResponse', {
bannerComment: '// Auto-generated types from API response',
enableConstEnums: false,
strictIndexSignatures: true,
});
// Write to file
fs.writeFileSync(outputPath, typeContent);
console.log(`✓ Types generated at ${outputPath}`);
}
function inferType(value: unknown): Record<string, unknown> {
if (value === null) return { type: 'null' };
if (typeof value === 'boolean') return { type: 'boolean' };
if (typeof value === 'number') return { type: 'number' };
if (typeof value === 'string') return { type: 'string' };
if (Array.isArray(value)) {
return {
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.
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)
Type Guard Generator
Generate TypeScript type guards
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.