惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

SecWiki News
SecWiki News
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
Visual Studio Blog
博客园 - 叶小钗
S
SegmentFault 最新的问题
IT之家
IT之家
大猫的无限游戏
大猫的无限游戏
博客园_首页
Apple Machine Learning Research
Apple Machine Learning Research
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
月光博客
月光博客
酷 壳 – CoolShell
酷 壳 – CoolShell
腾讯CDC
D
Darknet – Hacking Tools, Hacker News & Cyber Security
V
V2EX
阮一峰的网络日志
阮一峰的网络日志
L
Lohrmann on Cybersecurity
量子位
C
Cyber Attacks, Cyber Crime and Cyber Security
T
Tor Project blog
J
Java Code Geeks
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
博客园 - 三生石上(FineUI控件)
Attack and Defense Labs
Attack and Defense Labs
AI
AI
The Cloudflare Blog
T
Tailwind CSS Blog
S
Schneier on Security
爱范儿
爱范儿
PCI Perspectives
PCI Perspectives
Stack Overflow Blog
Stack Overflow Blog
S
Secure Thoughts
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
T
The Exploit Database - CXSecurity.com
博客园 - 【当耐特】
V2EX - 技术
V2EX - 技术
S
Securelist
P
Proofpoint News Feed
T
Threat Research - Cisco Blogs
Help Net Security
Help Net Security
C
Cisco Blogs
N
News and Events Feed by Topic
人人都是产品经理
人人都是产品经理
B
Blog RSS Feed
K
Kaspersky official blog
T
The Blog of Author Tim Ferriss
G
Google Developers Blog
S
Security Affairs
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Simon Willison's Weblog
Simon Willison's Weblog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
From JSON to TypeScript: Five Ways to Stop Hand-Writing Interfaces
Ashish Kumar · 2026-04-25 · via DEV Community

You've done it. We all have.

A new endpoint shows up. You curl it, get back eighty lines of nested JSON, and start typing:

interface User {
  id: string
  name: string
  // wait, is `email` always present?
}

Enter fullscreen mode Exit fullscreen mode

Twenty minutes later you've shipped it, ten minutes after that production is throwing Cannot read property 'name' of undefined because the API returns null for soft-deleted accounts, and you're patching it on the train home.

Hand-writing TypeScript interfaces from JSON responses is one of those tasks that looks like five minutes of work and is actually a slow drip of bugs. This post walks through five better ways to do it, the tradeoffs of each, and the specific failure modes you'll still need to watch for.

Why "just type it out" fails more than people admit

Three things go wrong when humans translate JSON to TypeScript:

You miss optional fields. The sample payload has email: "x@y.com" but the API spec says email can be omitted. Your interface has a non-optional email: string. The compiler is happy. Production isn't.

You confuse null and undefined. APIs love returning null for missing values. TypeScript loves using ? for optional. These aren't the same. email?: string means the key might not exist; email: string | null means the key exists but the value can be null. Mixing them silently is one of the most common ways type-safe code becomes type-theater.

You assume one sample tells the whole story. A field that comes back as ["admin"] in your sample is string[]. The same field returns [] for unprivileged users — and [] could just as easily have been number[] if you'd seen a different sample. Your "type-safe" code is now wrong half the time.

These aren't theoretical. They're a big chunk of the runtime bugs that survive code review in well-typed codebases. Auto-generation doesn't eliminate them, but it cuts the surface area dramatically.

Method 1 — Paste it into a browser tool

For one-off conversions during development, the lowest-friction option is a browser tool that converts JSON to TypeScript in real time. The JSON-to-TypeScript converter on json.renderlog.in runs entirely client-side — paste the JSON, copy the interface, done. Nothing leaves your browser, which matters when the JSON contains anything sensitive (auth tokens, internal IDs, customer data you shouldn't be uploading to a random web tool).

When this is the right tool:

  • Quick exploration ("what's the shape of this thing?")
  • Pairing with a teammate or screen-sharing in a meeting
  • One-time scripts where you just need to ship something today

When it isn't:

  • Anything that runs in CI
  • Repeatedly regenerating types from a moving schema
  • Type generation that needs to live alongside your API client

For repeated work, you want a CLI.

Method 2 — quicktype (the workhorse)

quicktype is the most flexible converter for production use. It reads JSON, JSON Schema, GraphQL, or TypeScript and outputs almost any language. For a Node project:

npx quicktype --src-lang json --lang typescript \
  --top-level User user-sample.json > types/user.ts

Enter fullscreen mode Exit fullscreen mode

It also handles arrays of samples, which is how you avoid the "single-sample lies" problem:

npx quicktype --src-lang json --lang typescript \
  --top-level Order order-1.json order-2.json order-3.json \
  > types/order.ts

Enter fullscreen mode Exit fullscreen mode

Feed it three or four real responses and it'll correctly mark fields as optional that appear in some samples but not others.

The catch: quicktype's defaults are conservative. If a field is null in even one sample, it widens to T | null. This is correct but can produce noisy types for fields that are only nullable in degenerate cases. Use --no-maps, --no-enums, and --no-combine-classes to control the output shape.

Method 3 — generate from a JSON Schema (the right way, if you have one)

If your API publishes an OpenAPI or JSON Schema, throw away the response-sniffing approach entirely. Generate directly from the schema:

npx json-schema-to-typescript schema.json -o types.d.ts

Enter fullscreen mode Exit fullscreen mode

This is the only method that's actually correct, because it uses the contract — not a snapshot of the contract on a particular Tuesday. If your backend doesn't publish a schema, this is the moment to push for one. It pays back forever.

For OpenAPI specifically, openapi-typescript is better:

npx openapi-typescript ./openapi.yaml -o ./src/api-types.ts

Enter fullscreen mode Exit fullscreen mode

You get path-typed clients, request/response unions, and discriminated unions where the spec defines them. Pair it with a tool like openapi-fetch and your API client becomes effectively impossible to call wrong.

Method 4 — Zod schemas, then infer

If your code already validates incoming JSON at runtime — and it should, at any system boundary — you don't need a separate type-generation step. Zod gives you both:

import { z } from 'zod'

const UserSchema = z.object({
  id: z.string().uuid(),
  email: z.string().email().nullable(),
  roles: z.array(z.enum(['admin', 'editor', 'viewer'])).default([]),
  createdAt: z.string().datetime(),
})

type User = z.infer<typeof UserSchema>

Enter fullscreen mode Exit fullscreen mode

User is now a fully typed interface, and UserSchema.parse(data) validates incoming JSON at runtime. The type and the validator can't drift apart because they're literally the same object.

This is the pattern I reach for in any new TypeScript service. Auto-generation from JSON is fine for exploration, but the contract for your runtime should be expressed in code, not in a sample file someone forgot to update.

For converting a JSON sample to a Zod schema, the JSON-to-Zod converter on json.renderlog.in handles the mechanical part. Generate the rough schema, then tighten the validation rules — adding .uuid(), .email(), length bounds, refinements — by hand. That's the part that actually deserves human attention; the boilerplate isn't.

Method 5 — going the other direction

Sometimes you have TypeScript types and need a JSON Schema (for documenting an API, generating OpenAPI specs, validating environment variables). ts-json-schema-generator does the reverse:

npx ts-json-schema-generator --path 'src/types.ts' \
  --type 'User' --out 'schema/user.json'

Enter fullscreen mode Exit fullscreen mode

This rounds out the toolkit. JSON ↔ TypeScript ↔ JSON Schema are all interconvertible; pick the direction that matches your source of truth and let tooling handle the rest.

Five mistakes auto-generation still makes

No tool is perfect. Here's what to fix by hand after generating:

1. Empty arrays infer as never[] (or worse, any[]). If your sample has roles: [], the generator can't know what type the array contains. Either feed it a sample with elements, or hand-edit to string[].

2. Optional vs nullable. Tools that infer from a single sample treat { email: null } as email: null (the literal type). You almost always want string | null. Multi-sample tools handle this better, but watch for it.

3. Discriminated unions get flattened. A field that's { kind: 'user', name: string } in one sample and { kind: 'org', members: number } in another should be a tagged union. Most generators merge them into one interface with everything optional. Fix manually:

// what you usually get
interface Account {
  kind: 'user' | 'org'
  name?: string
  members?: number
}

// what you actually want
type Account =
  | { kind: 'user'; name: string }
  | { kind: 'org'; members: number }

Enter fullscreen mode Exit fullscreen mode

The second form is the one that actually narrows in switch statements.

4. Date strings stay as strings. createdAt: "2026-04-25T10:00:00Z" types as string, not Date. That's technically correct for JSON over the wire, but you usually want a parse step that converts it on receive. Zod's .datetime() plus a .transform(s => new Date(s)) handles this in one shot.

5. The unspoken any. When the generator hits a deeply dynamic field (a metadata blob, a "custom fields" map, a field whose value is itself JSON-encoded), it falls back to any or unknown. Search the generated file for any before committing — it's the single biggest source of "we have TypeScript but our runtime still crashes."

A workflow that scales

Here's the pattern that holds up across teams:

  1. Source of truth in the schema — OpenAPI or JSON Schema, owned by the API team.
  2. Generated types in CIopenapi-typescript runs on every backend deploy, types get committed to a shared package consumed by the frontend.
  3. Runtime validation at the boundary — Zod (or Valibot, or Yup) at every fetch call, even for "trusted" internal services. Internal services lie.
  4. Hand-written types for derived shapes — UI state, reducers, props. Don't generate these.

The rule: types that come from an external system should be generated. Types that you create should be hand-written. Mixing the two — generating UI state from a sample API response — is how you end up with a User type that has a _internalShoppingCartId field nobody understands, two years later.

When you should not auto-generate

A few cases where the overhead isn't worth it:

  • Stable, small payloads. If the response is { ok: boolean, message: string }, just type it. Generation tooling is more code than the type itself.
  • Heavily customized types. If you're going to add readonly, branded types (type UserId = string & { __brand: 'UserId' }), or template-literal constraints, the generator output is a starting point you'll rewrite anyway.
  • One-time scripts. Don't add tooling to a five-line migration script. as any is a fine choice sometimes.

The honest answer is most production codebases benefit from generation, most exploratory code doesn't, and the gradient between them is what experienced engineers spend years calibrating.

A short detour: other JSON tools that pair well with this workflow

Type generation is one slice of the JSON-debugging work most engineers do every week. A few related browser tools that show up in the same workflow:

  • Compare two JSON responses — when a frontend works locally but breaks in staging, diffing the two payloads side-by-side finds the schema drift in 30 seconds.
  • Generate a JSON Schema from a sample — useful when you want to pin down a contract for an API that doesn't publish one yet.
  • JSONPath tester — for validating queries against a payload before wiring them into a jq script or a JS reducer.
  • JSON repair — handles trailing commas, missing quotes, and the other things that make JSON.parse throw in surprising ways.
  • JSON to Go struct, JSON to Python, JSON to CSV, JSON to YAML — same auto-generation idea, different target language.
  • JWT decoder — because half the time the "JSON" you're debugging is actually a base64-encoded token. (Worth its own post; coming next.)

All of these run client-side, so the JSON you paste never leaves your browser.

TL;DR

  • Stop hand-writing TypeScript types from JSON responses past trivial size.
  • For one-off shapes, paste into a browser tool like the JSON-to-TypeScript converter.
  • For repeatable, multi-sample inference: quicktype.
  • If your API has an OpenAPI/JSON Schema: generate from that, not from samples.
  • For runtime validation + types in one place: Zod with z.infer — start the schema with a JSON-to-Zod converter, then refine.
  • After generation, always check for: never[], accidental nullability, missed discriminated unions, date strings, and lurking anys.

Five minutes setting up the right generation pipeline saves you the slow drip of Cannot read property X of undefined bugs forever.


If this was useful, I've also built a handful of other free, browser-based tools — no signup, no uploads, everything runs client-side: