cd .. (alle tools)

JSON → TypeScript

Types en een Zod-schema uit een JSON-voorbeeld.

// Draait in je browser. Wat je hier typt wordt nergens heen gestuurd.

De types komen uit dit ene voorbeeld: een veld dat hier ontbreekt of null is, kan in andere data iets anders zijn.

TypeScript

export interface User {
  id: number;
  name: string;
  email: null;
  roles: string[];
  address: Address;
  orders: Order[];
}

export interface Order {
  id: number;
  total: number;
  paid: boolean;
  coupon?: string;
}

export interface Address {
  city: string;
  country: string;
}

Zod-schema

import { z } from 'zod';

const addressSchema = z.object({
  city: z.string(),
  country: z.string(),
});

const orderSchema = z.object({
  id: z.number(),
  total: z.number(),
  paid: z.boolean(),
  coupon: z.string().optional(),
});

export const userSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.null(),
  roles: z.array(z.string()),
  address: addressSchema,
  orders: z.array(orderSchema),
});

export type User = z.infer<typeof userSchema>;