Convertire JSON in TypeScript: Generare tipi automaticamente
Guida completa per convertire JSON in interfacce TypeScript. Strumenti online, CLI, VS Code extensions e best practices per type-safe development.
Big JSON Team
• Technical WriterExpert in JSON data manipulation, API development, and web technologies. Passionate about creating tools that make developers' lives easier.
# Convertire JSON in TypeScript: Generare tipi automaticamente
TypeScript richiede definizioni di tipo per i tuoi dati JSON. Questa guida ti mostrerà come generare automaticamente interfacce TypeScript da JSON, risparmiando tempo e riducendo errori.
Perché convertire JSON in TypeScript?
Vantaggi Type Safety
Senza tipi (JavaScript):const utente = JSON.parse(jsonString);
console.log(utente.nome); // ✅ OK
console.log(utente.nme); // ❌ Typo, ma nessun errore!
Con tipi (TypeScript):
interface Utente {
nome: string;
email: string;
età: number;
}
const utente: Utente = JSON.parse(jsonString);
console.log(utente.nome); // ✅ OK
console.log(utente.nme); // ❌ Error: Property 'nme' does not exist
Benefici
- Autocompletamento IDE - Suggerimenti intelligenti
- Refactoring sicuro - Trova tutti gli usi
- Documentazione automatica - Tipi come docs
- Catch errori compile-time - Non a runtime
- Performance migliore - Meno controlli runtime
Strumenti online
QuickType
URL: quicktype.io Funzionalità:- Multi-linguaggio (TS, C#, Go, etc.)
- Genera da JSON, JSON Schema
- Opzioni personalizzabili
- API disponibile
{
"nome": "Marco",
"età": 30,
"indirizzo": {
"città": "Roma",
"cap": "00100"
},
"hobby": ["coding", "reading"]
}
Output TypeScript:
export interface Utente {
nome: string;
età: number;
indirizzo: Indirizzo;
hobby: string[];
}
export interface Indirizzo {
città: string;
cap: string;
}
Transform Tools
URL: transform.tools/json-to-typescript Caratteristiche:- Interface mode
- Single file mode
- Configurable options
- Real-time preview
JSON2TS
URL: json2ts.com Semplice e veloce:- Paste JSON
- Get TypeScript
- Opzioni minime
VS Code Extensions
Paste JSON as Code
Installazione:1. Apri VS Code
Ctrl+P
ext install quicktype.quicktype
Reload
Uso:
- Windows/Linux: Ctrl+Shift+Alt+V
- Mac: Cmd+Shift+Opt+V
{
"id": 123,
"titolo": "Post di esempio",
"autore": {
"nome": "Laura",
"email": "laura@example.com"
},
"tag": ["typescript", "json"]
}
Paste as code → Genera:
export interface Post {
id: number;
titolo: string;
autore: Autore;
tag: string[];
}
export interface Autore {
nome: string;
email: string;
}
JSON to TS
Extension alternativa: Installazione:ext install MariusAlchimavicius.json-to-ts
Features:
- Click destro → Convert JSON to TS
- Opzioni configurabili
- Supporta commenti
CLI Tools
quicktype CLI
Installazione:npm install -g quicktype
Uso base:
# Da file JSON
quicktype data.json -o types.ts
# Da stdin
echo '{"nome":"Marco"}' | quicktype -o user.ts
# Con nome tipo
quicktype data.json -o types.ts --top-level User
Opzioni avanzate:
# Readonly properties
quicktype data.json -o types.ts --readonly
# Only types (no namespace)
quicktype data.json -o types.ts --just-types
# Multi-file
quicktype user.json -o types/user.ts product.json -o types/product.ts
Script npm:
{
"scripts": {
"generate-types": "quicktype data/.json -o src/types/generated.ts"
}
}
json-schema-to-typescript
Per JSON Schema → TS: Installazione:npm install -g json-schema-to-typescript
Uso:
json2ts -i schema.json -o types.ts
Programmatic use:
import { compile } from 'json-schema-to-typescript';
const schema = {
type: 'object',
properties: {
nome: { type: 'string' },
età: { type: 'number' }
},
required: ['nome']
};
const ts = await compile(schema, 'User');
console.log(ts);
Generazione programmatica
Node.js script
import as fs from 'fs';
import { quicktype, InputData, JSONSchemaInput } from 'quicktype-core';
async function jsonToTS(jsonString: string, typeName: string) {
const jsonInput = new JSONSchemaInput();
// Parse JSON
await jsonInput.addSource({
name: typeName,
schema: jsonString,
});
const inputData = new InputData();
inputData.addInput(jsonInput);
// Generate TypeScript
const result = await quicktype({
inputData,
lang: 'typescript',
rendererOptions: {
'just-types': 'true',
'nice-property-names': 'true',
'explicit-unions': 'true'
}
});
return result.lines.join('\n');
}
// Uso
const json = fs.readFileSync('data.json', 'utf-8');
const types = await jsonToTS(json, 'ApiResponse');
fs.writeFileSync('types.ts', types);
Build pipeline
Con Webpack:// webpack.config.js
const QuicktypeWebpackPlugin = require('quicktype-webpack-plugin');
module.exports = {
plugins: [
new QuicktypeWebpackPlugin({
input: './data/.json',
output: './src/types/generated.ts',
lang: 'typescript'
})
]
};
Casi d'uso pratici
1. API Response types
API response:{
"data": {
"utenti": [
{
"id": 1,
"username": "marco_dev",
"profilo": {
"avatar": "https://example.com/avatar.jpg",
"bio": "Developer"
},
"createdAt": "2026-01-20T10:00:00Z"
}
],
"pagination": {
"page": 1,
"totalPages": 10,
"totalItems": 100
}
},
"status": "success"
}
Generated types:
export interface ApiResponse {
data: Data;
status: string;
}
export interface Data {
utenti: Utente[];
pagination: Pagination;
}
export interface Utente {
id: number;
username: string;
profilo: Profilo;
createdAt: Date;
}
export interface Profilo {
avatar: string;
bio: string;
}
export interface Pagination {
page: number;
totalPages: number;
totalItems: number;
}
Uso con fetch:
async function getUsers(): Promise<ApiResponse> {
const response = await fetch('/api/users');
const data: ApiResponse = await response.json();
// Type-safe access
data.data.utenti.forEach(user => {
console.log(user.profilo.bio); // ✅ Autocomplete!
});
return data;
}
2. Config files
config.json:{
"app": {
"name": "MyApp",
"version": "1.0.0",
"features": {
"auth": true,
"darkMode": false
}
},
"database": {
"host": "localhost",
"port": 5432,
"credentials": {
"username": "admin",
"password": "secret"
}
}
}
Generated + usage:
export interface Config {
app: App;
database: Database;
}
export interface App {
name: string;
version: string;
features: Features;
}
export interface Features {
auth: boolean;
darkMode: boolean;
}
export interface Database {
host: string;
port: number;
credentials: Credentials;
}
export interface Credentials {
username: string;
password: string;
}
// Uso type-safe
import configJson from './config.json';
const config: Config = configJson;
if (config.app.features.auth) {
// Setup authentication
}
3. Test fixtures
test-data.json:{
"testCases": [
{
"name": "Valid user",
"input": { "email": "test@example.com" },
"expected": { "valid": true }
}
]
}
Test con tipi:
interface TestFixture {
testCases: TestCase[];
}
interface TestCase {
name: string;
input: Input;
expected: Expected;
}
import fixtures from './test-data.json';
const data: TestFixture = fixtures;
data.testCases.forEach(test => {
it(test.name, () => {
const result = validate(test.input);
expect(result).toEqual(test.expected);
});
});
Ottimizzazione tipi generati
1. Union types
JSON con varianti:[
{ "type": "circle", "radius": 10 },
{ "type": "rectangle", "width": 20, "height": 10 }
]
Generated (migliora con discriminated union):
// Auto-generated
type Shape = Circle | Rectangle;
interface Circle {
type: "circle";
radius: number;
}
interface Rectangle {
type: "rectangle";
width: number;
height: number;
}
// Uso type-safe
function getArea(shape: Shape): number {
switch (shape.type) {
case "circle":
return Math.PI shape.radius * 2;
case "rectangle":
return shape.width shape.height;
}
}
2. Optional properties
Aggiungi ? a campi opzionali:// Generated
interface User {
nome: string;
email: string;
bio: string | null;
}
// Migliorato
interface User {
nome: string;
email: string;
bio?: string; // Opzionale
}
3. Readonly
Per dati immutabili:interface User {
readonly id: number;
readonly createdAt: Date;
nome: string; // Modificabile
}
Best practices
1. Genera da schema quando possibile
✅ JSON Schema → TypeScript
❌ JSON instance → TypeScript
Perché:- Schema definisce tutti i casi
- Instance è un solo esempio
- Schema ha constraints
2. Organizza tipi in file dedicati
src/
types/
api.ts # API types
models.ts # Domain models
config.ts # Config types
generated/ # Auto-generated
users.ts
products.ts
3. Versiona tipi con API
// types/api/v1.ts
export namespace APIv1 {
export interface User { ... }
}
// types/api/v2.ts
export namespace APIv2 {
export interface User { ... }
}
4. Commenta differenze da JSON
export interface ApiResponse {
// JSON: "2026-01-26T10:00:00Z"
// Convertito in Date object
createdAt: Date;
// JSON può essere null
description?: string;
}
5. Valida a runtime
TypeScript tipi spariscono a runtime:import { z } from 'zod';
// Define schema
const UserSchema = z.object({
nome: z.string(),
età: z.number().min(0),
email: z.string().email()
});
// TypeScript type da schema
type User = z.infer<typeof UserSchema>;
// Runtime validation
function parseUser(json: unknown): User {
return UserSchema.parse(json); // Throws se invalido
}
Conclusione
Strumenti consigliati:- Online: QuickType.io
- VS Code: Paste JSON as Code extension
- CLI: quicktype per automation
- Runtime validation: Zod, io-ts
Generare tipi da JSON automaticamente ti risparmia ore di lavoro e previene innumerevoli bugs!
Articoli Correlati
Migliori strumenti JSON online 2026: Guida completa
Scopri i migliori strumenti JSON online per formattare, validare, convertire e visualizzare JSON. Confronto dettagliato con esempi pratici.
JavaScript e JSON: Guida completa a JSON.parse() e JSON.stringify()
Guida completa su JSON in JavaScript: parsing, serializzazione, gestione errori, localStorage, fetch API e best practices. Include esempi pratici e troubleshooting.
Comprendere JSON Schema: Validazione e documentazione dati
Guida completa a JSON Schema: validazione dati, tipi, vincoli, pattern, esempi pratici e librerie. Impara a validare e documentare API JSON professionalmente.