Générer des types TypeScript depuis une API

VérifiéPrudence

Génère des interfaces TypeScript à partir de réponses API ou de schémas OpenAPI. Utilisez-le pour typer des réponses, créer des interfaces depuis du JSON ou synchroniser les types.

Spar Skills Guide Bot
DeveloppementIntermédiaire
25/07/2026
Claude CodeCursorWindsurfCopilot
#typescript#api-types#openapi#code-generation#type-inference

Recommandé pour

Synthèse automatique

Génère des interfaces TypeScript à partir de réponses JSON d'API ou de schémas OpenAPI/Swagger, avec règles d'inférence de types et commentaires JSDoc.

Points forts

  • Fournit une table d'inférence claire (null, tableaux vides, dates ISO, UUID) qui évite les choix arbitraires
  • Couvre les cas délicats : objets imbriqués, tableaux d'objets, tuples à longueur fixe, champs optionnels détectés sur plusieurs échantillons
  • Propose des branded types réutilisables (UUID, Email, ISODateString) pour les chaînes à sémantique particulière
  • Distingue l'approche selon la source : JSON collé, OpenAPI, GraphQL ou endpoint live

Limites

  • La qualité des types dépend entièrement des échantillons fournis : un payload partiel produira des types incomplets ou une nullabilité erronée
  • Aucune validation à l'exécution n'est générée (pas de schéma Zod ou équivalent), les types restent effacés au runtime
  • Les branded types demandent un câblage manuel côté parsing pour être réellement contraignants
Quand l'utiliser

À utiliser quand vous avez un payload JSON ou une spec OpenAPI sous la main et voulez des interfaces TypeScript typées et documentées rapidement.

Quand l'éviter

À éviter si vous avez besoin de validation runtime ou de types synchronisés automatiquement en CI, cas où un générateur relié au schéma source est plus adapté.

Analyse de sécurité

Prudence
Score qualité88/100

The skill is benign TypeScript type-generation guidance, but it does involve legitimate use of network, npm, and npx commands. Because those tools can execute remote packages and fetch external resources, it warrants caution rather than a pure safe rating.

Points d'attention
  • •No allowed-tools are declared, but the skill includes shell commands (`npm install`, `npx`) and recommends fetching live endpoints/remote OpenAPI schemas.
  • •The `npx openapi-typescript <url>` examples use an unpinned package and remote URL input, so the agent may execute network-fetched tooling and process untrusted schemas.
  • •No destructive, exfiltration, or obfuscated behavior is present.
Comment cette analyse est faite

Exemples

Type a JSON payload
Here's a sample response from our /users endpoint. Generate TypeScript interfaces for it, with nested objects split into their own types and JSDoc on each field.
From OpenAPI spec
Generate TypeScript types from this OpenAPI schema for the orders and line-items endpoints, and put them in types/api/.
Nullable and optional fields
I have three sample responses from the same endpoint — infer which fields are optional or nullable and generate a single interface that covers all three.

name: generating-typescript-types-from-apis description: Generates TypeScript interfaces from API responses or OpenAPI schemas. Use when the user asks about typing API responses, creating interfaces from JSON, parsing Swagger/OpenAPI, or keeping types in sync with backend.

API Response → TypeScript Types

When to use this skill

  • User asks to type an API response
  • User has JSON and needs TypeScript interfaces
  • User mentions OpenAPI or Swagger schemas
  • User wants to generate types from endpoints
  • User asks about keeping frontend/backend types in sync

Workflow

  • [ ] Identify API source (JSON response, OpenAPI, endpoint)
  • [ ] Parse response structure
  • [ ] Generate TypeScript interfaces
  • [ ] Handle nested objects and arrays
  • [ ] Add JSDoc comments
  • [ ] Export types to appropriate location

Instructions

Step 1: Identify Source Type

| Source | Approach | | --------------- | --------------------- | | JSON response | Parse and infer types | | OpenAPI/Swagger | Use generator tool | | GraphQL | Use codegen | | Live endpoint | Fetch and parse |

Step 2: Parse JSON Response

Sample API response:

{
  "id": 123,
  "name": "John Doe",
  "email": "john@example.com",
  "isActive": true,
  "roles": ["admin", "user"],
  "profile": {
    "avatar": "https://example.com/avatar.jpg",
    "bio": null,
    "socialLinks": [
      { "platform": "twitter", "url": "https://twitter.com/john" }
    ]
  },
  "createdAt": "2026-01-18T10:00:00Z",
  "metadata": {}
}

Generated TypeScript:

// types/api/user.ts

export interface User {
  /** Unique identifier */
  id: number;
  /** User's full name */
  name: string;
  /** Email address */
  email: string;
  /** Whether the user account is active */
  isActive: boolean;
  /** Assigned roles */
  roles: string[];
  /** User profile information */
  profile: UserProfile;
  /** Account creation timestamp (ISO 8601) */
  createdAt: string;
  /** Additional metadata */
  metadata: Record<string, unknown>;
}

export interface UserProfile {
  /** Avatar image URL */
  avatar: string;
  /** User biography */
  bio: string | null;
  /** Social media links */
  socialLinks: SocialLink[];
}

export interface SocialLink {
  /** Platform name */
  platform: string;
  /** Profile URL */
  url: string;
}

Step 3: Type Inference Rules

| JSON Value | TypeScript Type | | --------------- | --------------------------- | | 123 | number | | "text" | string | | true/false | boolean | | null | null (or T \| null) | | [] | T[] (infer from items) | | {} empty | Record<string, unknown> | | {} with keys | Named interface | | ISO date string | string (add comment) | | UUID string | string (add branded type) |

Branded types for special strings:

// types/branded.ts
export type UUID = string & { readonly __brand: "UUID" };
export type ISODateString = string & { readonly __brand: "ISODateString" };
export type Email = string & { readonly __brand: "Email" };

// Usage
export interface User {
  id: UUID;
  email: Email;
  createdAt: ISODateString;
}

Step 4: Handle Arrays

Homogeneous array:

// JSON: [1, 2, 3]
items: number[];

// JSON: ["a", "b"]
tags: string[];

Array of objects:

// JSON: [{ "id": 1, "name": "Item" }]
items: Item[];

interface Item {
  id: number;
  name: string;
}

Mixed array (avoid if possible):

// JSON: [1, "two", true]
values: (number | string | boolean)[];

Tuple (fixed length, known types):

// JSON: [37.7749, -122.4194] (lat/lng)
coordinates: [number, number];

Step 5: Handle Optional Fields

Detect optional fields from multiple samples:

// Sample 1: { "name": "John", "nickname": "Johnny" }
// Sample 2: { "name": "Jane" }

export interface User {
  name: string;
  nickname?: string; // Optional - not present in all responses
}

Nullable vs optional:

export interface User {
  bio: string | null; // Present but can be null
  nickname?: string; // May not be present
  avatar?: string | null; // May not be present, or null
}

Step 6: API Response Wrappers

Paginated response:

export interface PaginatedResponse<T> {
  data: T[];
  pagination: {
    page: number;
    perPage: number;
    total: number;
    totalPages: number;
  };
}

// Usage
type UsersResponse = PaginatedResponse<User>;

API envelope:

export interface ApiResponse<T> {
  success: boolean;
  data: T;
  error?: ApiError;
}

export interface ApiError {
  code: string;
  message: string;
  details?: Record<string, string[]>;
}

// Usage
type UserResponse = ApiResponse<User>;
type UsersResponse = ApiResponse<User[]>;

Step 7: OpenAPI/Swagger Generation

Using openapi-typescript:

npm install -D openapi-typescript
# From URL
npx openapi-typescript https://api.example.com/openapi.json -o types/api.ts

# From local file
npx openapi-typescript ./openapi.yaml -o types/api.ts

# Watch mode
npx openapi-typescript ./openapi.yaml -o types/api.ts --watch

Generated usage:

import type { paths, components } from "./types/api";

// Extract response type
type User = components["schemas"]["User"];

// Extract endpoint types
type GetUsersResponse =
  paths["/users"]["get"]["responses"]["200"]["content"]["application/json"];
type CreateUserBody =
  paths["/users"]["post"]["requestBody"]["content"]["application/json"];

With openapi-fetch for type-safe requests:

npm install openapi-fetch
import createClient from "openapi-fetch";
import type { paths } from "./types/api";

const client = createClient<paths>({ baseUrl: "https://api.example.com" });

// Fully typed request/response
const { data, error } = await client.GET("/users/{id}", {
  params: { path: { id: "123" } },
});
// data is typed as User

Step 8: Fetch and Generate Script

// scripts/generate-types.ts
import { writeFileSync } from "fs";

interface TypeDefinition {
  name: string;
  properties: PropertyDefinition[];
}

interface PropertyDefinition {
  name: string;
  type: string;
  optional: boolean;
  nullable: boolean;
  comment?: string;
}

function inferType(value: unknown, key: string): string {
  if (value === null) return "null";
  if (Array.isArray(value)) {
    if (value.length === 0) return "unknown[]";
    const itemType = inferType(value[0], `${key}Item`);
    return `${itemType}[]`;
  }
  if (typeof value === "object") {
    return toPascalCase(key);
  }
  return typeof value;
}

function toPascalCase(str: string): string {
  return str.replace(/(^|_)(\w)/g, (_, __, c) => c.toUpperCase());
}

function generateInterface(
  name: string,
  obj: Record<string, unknown>,
): string[] {
  const lines: string[] = [];
  const nested: string[] = [];

  lines.push(`export interface ${name} {`);

  for (const [key, value] of Object.entries(obj)) {
    const type = inferType(value, key);
    const nullable = value === null ? " | null" : "";

    if (typeof value === "object" && value !== null && !Array.isArray(value)) {
      nested.push(
        ...generateInterface(
          toPascalCase(key),
          value as Record<string, unknown>,
        ),
      );
    }

    lines.push(`  ${key}: ${type}${nullable};`);
  }

  lines.push("}");
  lines.push("");

  return [...nested, ...lines];
}

async function main() {
  const response = await fetch("https://api.example.com/users/1");
  const data = await response.json();

  const types = generateInterface("User", data);
  const output = types.join("\n");

  writeFileSync("types/user.ts", output);
  console.log("Generated types/user.ts");
}

main();

Step 9: Keep Types in Sync

CI check for OpenAPI changes:

# .github/workflows/types.yml
name: Generate API Types

on:
  schedule:
    - cron: "0 0 * * *" # Daily
  workflow_dispatch:

jobs:
  generate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Generate types
        run: npx openapi-typescript ${{ vars.API_SPEC_URL }} -o types/api.ts

      - name: Check for changes
        id: changes
        run: |
          if git diff --quiet types/api.ts; then
            echo "changed=false" >> $GITHUB_OUTPUT
          else
            echo "changed=true" >> $GITHUB_OUTPUT
          fi

      - name: Create PR
        if: steps.changes.outputs.changed == 'true'
        uses: peter-evans/create-pull-request@v5
        with:
          title: "chore: update API types"
          branch: update-api-types

Pre-commit hook:

# .husky/pre-commit
npx openapi-typescript ./openapi.yaml -o types/api.ts
git add types/api.ts

Output Location

types/
├── api/
│   ├── user.ts       # User-related types
│   ├── product.ts    # Product types
│   └── index.ts      # Re-exports
├── api.ts            # OpenAPI generated (single file)
└── branded.ts        # Branded types (UUID, Email, etc.)

Index file:

// types/api/index.ts
export * from "./user";
export * from "./product";
export type { ApiResponse, ApiError, PaginatedResponse } from "./common";

Validation

Before completing:

  • [ ] All interfaces have JSDoc comments
  • [ ] Nested objects have named interfaces
  • [ ] Optional fields marked with ?
  • [ ] Nullable fields use | null
  • [ ] Arrays are properly typed
  • [ ] No any types in output
  • [ ] Types compile without errors
# Validate generated types
npx tsc --noEmit types/**/*.ts

Error Handling

  • Empty object {}: Use Record<string, unknown> not object.
  • Mixed arrays: Union type or unknown[]; flag for manual review.
  • Circular references: OpenAPI generators handle this; manual parsing needs tracking.
  • Conflicting samples: Mark field as optional with union of observed types.
  • Unknown date format: Default to string with JSDoc explaining format.

Resources

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/generate-typescript-types-from-apis-mrzxuqg8/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/generate-typescript-types-from-apis-mrzxuqg8' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/generate-typescript-types-from-apis-mrzxuqg8/download' --output '.skill-downloads/generate-typescript-types-from-apis-mrzxuqg8/SKILL.md.part' && mv '.skill-downloads/generate-typescript-types-from-apis-mrzxuqg8/SKILL.md.part' '.skill-downloads/generate-typescript-types-from-apis-mrzxuqg8/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/generate-typescript-types-from-apis-mrzxuqg8/SKILL.md' && test -s '.skill-downloads/generate-typescript-types-from-apis-mrzxuqg8/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/generating-typescript-types-from-apis' && cp -R '.skill-downloads/generate-typescript-types-from-apis-mrzxuqg8' '.claude/skills/generating-typescript-types-from-apis'

Cursor
test -f '.skill-downloads/generate-typescript-types-from-apis-mrzxuqg8/SKILL.md' && test -s '.skill-downloads/generate-typescript-types-from-apis-mrzxuqg8/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/generating-typescript-types-from-apis' && cp -R '.skill-downloads/generate-typescript-types-from-apis-mrzxuqg8' '.cursor/skills/generating-typescript-types-from-apis'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/generate-typescript-types-from-apis-mrzxuqg8'

openskills read 'generate-typescript-types-from-apis-mrzxuqg8'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/generate-typescript-types-from-apis-mrzxuqg8/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires