Skip to content

CLI Type Generator

Sebastian Martinez edited this page Apr 2, 2026 · 2 revisions

🔤 CLI Type Generator

🇺🇸 English: Automatically generate TypeScript interfaces from any JSON API response. One command turns a live endpoint into fully-typed code. 🇪🇸 Español: Genera automáticamente interfaces TypeScript a partir de cualquier respuesta JSON de una API. Un solo comando convierte un endpoint en código completamente tipado.


¿Qué hace? / What Does It Do?

ES: El modo --type del CLI de Bytekit hace una petición HTTP a la URL indicada, analiza la respuesta JSON y genera recursivamente interfaces TypeScript que representan la estructura exacta de los datos.

EN: The --type mode of the Bytekit CLI makes an HTTP request to the given URL, analyzes the JSON response, and recursively generates TypeScript interfaces representing the exact data structure.

bytekit --type https://jsonplaceholder.typicode.com/users/1
# ✅ Types generated → src/types/users.ts

Uso desde la terminal / Terminal Usage

bytekit --type [options] <url>

Opciones compatibles / Compatible Options

Option Description (EN) Descripción (ES)
--method=<METHOD> HTTP method (GET, POST, PUT, PATCH, DELETE). Default: GET Método HTTP. Por defecto: GET
--body=<json> JSON body for the request Cuerpo JSON para la petición
--header=<key:val> Custom header (repeatable) Cabecera personalizada (repetible)
--headers=<key:val> Alias for --header Alias de --header

⚠️ v3 — HTTPS enforcement / Forzado de HTTPS

EN: Since v3, the CLI rejects remote http:// URLs. Only https:// is allowed for remote hosts. http://localhost and loopback addresses (127.0.0.1, ::1) remain allowed for local development.

ES: Desde v3, el CLI rechaza URLs remotas con http://. Solo se permite https:// para hosts remotos. http://localhost y direcciones de loopback (127.0.0.1, ::1) siguen permitidas para desarrollo local.


Ejemplos / Examples

GET simple

bytekit --type https://jsonplaceholder.typicode.com/posts/1

ES: Genera src/types/posts.ts:

EN: Generates src/types/posts.ts:

// Auto-generated types from API response
// Generated at 2026-03-27T12:00:00.000Z

export interface Posts {
  userId: number;
  id: number;
  title: string;
  body: string;
}

POST con body

bytekit --type --method=POST \
  --body='{"name":"Ada Lovelace","email":"ada@example.com"}' \
  https://api.example.com/users

Con cabeceras de autenticación / With auth headers

bytekit --type \
  --header="Authorization:Bearer eyJhbGci..." \
  --header="Accept:application/json" \
  https://api.example.com/me

API interna / Internal API

ES: Internamente, el CLI delega en la función generateTypesFromEndpoint del módulo src/cli/type-generator.ts.

EN: Internally, the CLI delegates to the generateTypesFromEndpoint function from the src/cli/type-generator.ts module.

generateTypesFromEndpoint(options: TypeGeneratorOptions)

interface TypeGeneratorOptions {
  endpoint: string;                                      // URL to fetch
  method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; // Default: 'GET'
  output?: string;                                       // Default: 'types.ts'
  name?: string;                                         // Default: 'ApiResponse'
  headers?: Record<string, string>;                      // Custom headers
  body?: string;                                         // JSON body
}

ES: Cuando se llama desde el CLI, output se resuelve automáticamente a src/types/{endpoint}.ts y name se deriva del último segmento de la URL en PascalCase.

EN: When called from the CLI, output is automatically resolved to src/types/{endpoint}.ts and name is derived from the last URL segment in PascalCase.


Algoritmo de inferencia / Inference Algorithm

ES: El generador recorre recursivamente la estructura JSON y mapea cada tipo de dato JavaScript a su equivalente TypeScript.

EN: The generator recursively walks the JSON structure and maps each JavaScript data type to its TypeScript equivalent.

Tabla de mapeo / Mapping Table

JSON Value TypeScript Output Ejemplo / Example
null null "field?: null"
undefined undefined "field?: undefined"
true / false boolean "active: boolean"
42 / 3.14 number "count: number"
"hello" string "name: string"
[] (empty) unknown[] "items: unknown[]"
[1, 2, 3] number[] "ids: number[]"
[1, "a"] (mixed) (number | string)[] "values: (number | string)[]"
{ key: val } export interface / inline { } See below

Propiedades opcionales / Optional Properties

ES: Las propiedades con valor null o undefined se marcan automáticamente como opcionales (?):

EN: Properties with null or undefined values are automatically marked as optional (?):

{ "name": "Ada", "middleName": null, "nickname": undefined }
export interface ApiResponse {
  name: string;
  middleName?: null;
  nickname?: undefined;
}

Objetos anidados / Nested Objects

ES: Los objetos anidados se convierten en tipos inline dentro de la interfaz padre:

EN: Nested objects become inline types within the parent interface:

{
  "user": {
    "name": "Ada",
    "address": {
      "city": "London",
      "zip": "SW1A 1AA"
    }
  }
}
export interface ApiResponse {
  user: {
    name: string;
    address: {
      city: string;
      zip: string;
    };
  };
}

Arrays con tipos mixtos / Arrays with Mixed Types

ES: Si un array contiene elementos de distintos tipos, se genera un tipo unión:

EN: If an array contains elements of different types, a union type is generated:

{
  "data": [1, "two", true, null]
}
export interface ApiResponse {
  data: (number | string | boolean | null)[];
}

Flujo completo / Full Flow

ES: Paso a paso de lo que sucede cuando ejecutas bytekit --type:

EN: Step-by-step breakdown of what happens when you run bytekit --type:

1. CLI parsea argv → extrae URL, método, body, headers
   CLI parses argv → extracts URL, method, body, headers

2. Calcula nombre del archivo de salida desde el pathname de la URL
   Computes output filename from the URL pathname
   e.g. https://api.example.com/users → src/types/users.ts

3. Calcula nombre de la interfaz (PascalCase del endpoint)
   Computes interface name (PascalCase of endpoint)
   e.g. /users → Users

4. Llama a generateTypesFromEndpoint()
   Calls generateTypesFromEndpoint()

5. Hace fetch() con el método/headers/body indicados
   Performs fetch() with the given method/headers/body

6. Parsea la respuesta JSON
   Parses JSON response

7. Recorre recursivamente la estructura para inferir tipos
   Recursively walks the structure to infer types

8. Escribe el archivo .ts con comentario de timestamp
   Writes the .ts file with a timestamp comment

Uso programático / Programmatic Usage

ES: También puedes usar la función directamente en tu código Node.js/TypeScript:

EN: You can also use the function directly in your Node.js/TypeScript code:

import { generateTypesFromEndpoint } from "bytekit/cli/type-generator";

await generateTypesFromEndpoint({
  endpoint: "https://api.example.com/products",
  method: "GET",
  output: "src/types/products.ts",
  name: "Product",
  headers: {
    Authorization: "Bearer my-token",
  },
});

Ejemplo completo / Full Example

ES: Caso real: tipar la respuesta de la API de GitHub.

EN: Real-world case: typing the GitHub API response.

bytekit --type \
  --header="Accept:application/vnd.github.v3+json" \
  --header="User-Agent:bytekit-cli" \
  https://api.github.com/repos/nicobytes/bytekit

ES: Genera src/types/bytekit.ts con algo como:

EN: Generates src/types/bytekit.ts with something like:

// Auto-generated types from API response
// Generated at 2026-03-27T12:00:00.000Z

export interface Bytekit {
  id: number;
  name: string;
  full_name: string;
  private: boolean;
  owner: {
    login: string;
    id: number;
    avatar_url: string;
    url: string;
  };
  html_url: string;
  description: string;
  fork: boolean;
  url: string;
  stargazers_count: number;
  watchers_count: number;
  language: string;
  default_branch: string;
}

Errores comunes / Common Errors

Error Cause (EN) Causa (ES)
HTTP 401: Unauthorized Missing or invalid auth header Falta cabecera de autenticación o es inválida
HTTP 404: Not Found Wrong URL or endpoint doesn't exist URL incorrecta o el endpoint no existe
Unexpected token < in JSON Endpoint returned HTML instead of JSON El endpoint devolvió HTML en vez de JSON
Error: Missing URL No URL provided after --type No se proporcionó URL después de --type

Véase También / See Also

  • CLI Overview — Vista general de todos los modos del CLI / Overview of all CLI modes
  • CLI Swagger Generator — Generar DTOs desde specs OpenAPI / Generate DTOs from OpenAPI specs
  • ApiClient — Cliente HTTP de Bytekit / Bytekit HTTP client
  • SchemaAdapter — Adaptador y validación de esquemas / Schema adapter and validation

Clone this wiki locally