← Retour au Blog

Convertir JSON en TypeScript : Types, interfaces et génération automatique

Apprenez à générer des types TypeScript depuis JSON. Guide complet avec outils, techniques et meilleures pratiques pour un code type-safe.

Big JSON Team12 min de lectureprogramming
B

Big JSON Team

Technical Writer

Expert in JSON data manipulation, API development, and web technologies. Passionate about creating tools that make developers' lives easier.

12 min de lecture

# Convertir JSON en TypeScript : Types, interfaces et génération automatique

TypeScript ajoute la sécurité des types à JavaScript. Ce guide vous montre comment générer des types TypeScript depuis vos données JSON.

Pourquoi générer des types depuis JSON ?

  • Type safety : Détection d'erreurs à la compilation
  • IntelliSense : Autocomplétion dans l'éditeur
  • Documentation : Types servent de documentation
  • Refactoring : Modifications sûres

Conversion manuelle

JSON simple

Données JSON :

\\\json

{

"nom": "Jean Dupont",

"age": 30,

"email": "jean@exemple.com",

"actif": true

}

\\\

Interface TypeScript :

\\\typescript

interface Utilisateur {

nom: string;

age: number;

email: string;

actif: boolean;

}

\\\

JSON avec tableaux

JSON :

\\\json

{

"utilisateurs": [

{"id": 1, "nom": "Alice"},

{"id": 2, "nom": "Bob"}

]

}

\\\

TypeScript :

\\\typescript

interface Utilisateur {

id: number;

nom: string;

}

interface Reponse {

utilisateurs: Utilisateur[];

}

\\\

JSON imbriqué

JSON :

\\\json

{

"utilisateur": {

"nom": "Jean",

"adresse": {

"rue": "123 Rue Main",

"ville": "Paris"

}

}

}

\\\

TypeScript :

\\\typescript

interface Adresse {

rue: string;

ville: string;

}

interface Utilisateur {

nom: string;

adresse: Adresse;

}

interface Donnees {

utilisateur: Utilisateur;

}

\\\

Outils de génération automatique

QuickType (Recommandé)

En ligne : quicktype.io CLI Installation :

\\\bash

npm install -g quicktype

\\\

Utilisation :

\\\bash

# Depuis fichier JSON

quicktype data.json -o types.ts

# Depuis URL

quicktype https://api.example.com/user -o User.ts

# Avec options

quicktype data.json -o types.ts --just-types

\\\

Exemple : Input (data.json) :

\\\json

{

"utilisateurs": [

{

"id": 1,

"nom": "Alice",

"email": "alice@ex.com",

"createdAt": "2026-01-16T10:00:00Z"

}

]

}

\\\

Output (types.ts) :

\\\typescript

export interface Root {

utilisateurs: Utilisateur[];

}

export interface Utilisateur {

id: number;

nom: string;

email: string;

createdAt: Date;

}

// Code de conversion

export function toRoot(json: string): Root {

return JSON.parse(json);

}

\\\

json2ts

En ligne : json2ts.com CLI :

\\\bash

npm install -g json2ts

# Utilisation

json2ts data.json

\\\

VS Code Extension

Extension : "Paste JSON as Code"
  • Copier JSON
  • Cmd/Ctrl + Shift + P
  • "Paste JSON as Types"
  • Choisir TypeScript
  • Génération programmatique

    Avec json-schema-to-typescript

    \\\bash

    npm install json-schema-to-typescript

    \\\

    \\\typescript

    import {compile} from 'json-schema-to-typescript';

    const schema = {

    type: "object",

    properties: {

    nom: {type: "string"},

    age: {type: "number"}

    },

    required: ["nom"]

    };

    compile(schema, 'Utilisateur').then(ts => {

    console.log(ts);

    });

    // Output:

    /

    export interface Utilisateur {

    nom: string;

    age?: number;

    }

    /

    \\\

    Types avancés

    Unions

    JSON avec types variés :

    \\\json

    {

    "valeur": "texte"

    }

    // ou

    {

    "valeur": 42

    }

    \\\

    TypeScript :

    \\\typescript

    interface Donnees {

    valeur: string | number;

    }

    \\\

    Optionals

    JSON (propriété parfois absente) :

    \\\json

    {

    "nom": "Jean",

    "age": 30

    }

    // ou

    {

    "nom": "Alice"

    }

    \\\

    TypeScript :

    \\\typescript

    interface Utilisateur {

    nom: string;

    age?: number; // Optionnel

    }

    \\\

    Enums

    JSON avec valeurs fixes :

    \\\json

    {

    "role": "admin"

    }

    \\\

    TypeScript :

    \\\typescript

    enum Role {

    Admin = "admin",

    User = "user",

    Guest = "guest"

    }

    interface Utilisateur {

    role: Role;

    }

    // Ou type literal

    type RoleType = "admin" | "user" | "guest";

    interface Utilisateur {

    role: RoleType;

    }

    \\\

    Generics

    JSON avec structure répétitive :

    \\\json

    {

    "status": "success",

    "data": {

    "user": {...}

    }

    }

    \\\

    TypeScript :

    \\\typescript

    interface ApiResponse {

    status: "success" | "error";

    data: T;

    }

    interface Utilisateur {

    nom: string;

    age: number;

    }

    type ReponseUtilisateur = ApiResponse<{user: Utilisateur}>;

    \\\

    Validation runtime avec Zod

    \\\typescript

    import {z} from 'zod';

    // Définir schéma

    const UtilisateurSchema = z.object({

    nom: z.string(),

    age: z.number().min(0).max(120),

    email: z.string().email()

    });

    // Inférer type

    type Utilisateur = z.infer;

    // Valider données

    const data = {

    nom: "Jean",

    age: 30,

    email: "jean@ex.com"

    };

    try {

    const utilisateur = UtilisateurSchema.parse(data);

    // utilisateur est typé comme Utilisateur

    } catch (error) {

    console.error("Validation échouée:", error);

    }

    \\\

    Workflow complet

    1. Recevoir JSON API

    \\\typescript

    // Récupérer données

    const response = await fetch('https://api.example.com/users');

    const data = await response.json();

    // Pas de types pour 'data' ❌

    console.log(data.nom); // Pas d'autocomplétion

    \\\

    2. Générer types

    \\\bash

    # Sauvegarder exemple JSON

    curl https://api.example.com/users > users.json

    # Générer types

    quicktype users.json -o types/Users.ts

    \\\

    3. Utiliser types

    \\\typescript

    import {Utilisateur} from './types/Users';

    async function getUtilisateurs(): Promise {

    const response = await fetch('https://api.example.com/users');

    const data = await response.json();

    return data as Utilisateur[];

    }

    // Maintenant avec types ✓

    const users = await getUtilisateurs();

    console.log(users[0].nom); // Autocomplétion !

    \\\

    NPM Scripts

    package.json :

    \\\json

    {

    "scripts": {

    "generate:types": "quicktype src/data/.json -o src/types/",

    "generate:api-types": "quicktype https://api.ex.com/schema -o src/types/Api.ts"

    }

    }

    \\\

    \\\bash

    npm run generate:types

    \\\

    Meilleures pratiques

    1. Organiser les types

    \\\

    src/

    types/

    User.ts

    Product.ts

    Api.ts

    index.ts

    \\\

    2. Exporter types

    \\\typescript

    // types/index.ts

    export from './User';

    export from './Product';

    export from './Api';

    \\\

    3. Utiliser readonly

    \\\typescript

    interface Utilisateur {

    readonly id: number;

    nom: string;

    email: string;

    }

    \\\

    4. Types vs Interfaces

    \\\typescript

    // Interface (recommandé pour objets)

    interface Utilisateur {

    nom: string;

    }

    // Type (pour unions, intersections)

    type ID = string | number;

    type Admin = Utilisateur & {permissions: string[]};

    \\\

    5. Valider à runtime

    \\\typescript

    function isUtilisateur(obj: any): obj is Utilisateur {

    return typeof obj.nom === 'string' &&

    typeof obj.age === 'number';

    }

    if (isUtilisateur(data)) {

    // TypeScript sait que data est Utilisateur

    console.log(data.nom);

    }

    \\\

    Outils en ligne

  • QuickType : quicktype.io
  • json2ts : json2ts.com
  • Transform : transform.tools/json-to-typescript
  • JSON to TS : jsontots.com
  • Conclusion

    Workflow recommandé :
  • Obtenir JSON exemple (API, fichier)
  • Générer types (QuickType)
  • Valider runtime (Zod)
  • Utiliser dans code type-safe
  • Avantages TypeScript + JSON :
    • Erreurs détectées à la compilation
    • IntelliSense puissant
    • Code auto-documenté
    • Refactoring sécurisé

    Adoptez TypeScript pour un code JSON robuste !

    Share:

    Articles Connexes

    Read in English