-
Notifications
You must be signed in to change notification settings - Fork 1
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.
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.tsbytekit --type [options] <url>| 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 HTTPSEN: Since v3, the CLI rejects remote
http://URLs. Onlyhttps://is allowed for remote hosts.http://localhostand loopback addresses (127.0.0.1,::1) remain allowed for local development.ES: Desde v3, el CLI rechaza URLs remotas con
http://. Solo se permitehttps://para hosts remotos.http://localhosty direcciones de loopback (127.0.0.1,::1) siguen permitidas para desarrollo local.
bytekit --type https://jsonplaceholder.typicode.com/posts/1ES: 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;
}bytekit --type --method=POST \
--body='{"name":"Ada Lovelace","email":"ada@example.com"}' \
https://api.example.com/usersbytekit --type \
--header="Authorization:Bearer eyJhbGci..." \
--header="Accept:application/json" \
https://api.example.com/meES: 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.
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.
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.
| 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 |
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;
}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;
};
};
}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)[];
}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
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",
},
});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/bytekitES: 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;
}| 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
|
- 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