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

推荐订阅源

让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
人人都是产品经理
人人都是产品经理
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
T
The Exploit Database - CXSecurity.com
N
News and Events Feed by Topic
Latest news
Latest news
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
CXSECURITY Database RSS Feed - CXSecurity.com
IT之家
IT之家
V
V2EX
WordPress大学
WordPress大学
Apple Machine Learning Research
Apple Machine Learning Research
Cisco Talos Blog
Cisco Talos Blog
K
Kaspersky official blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
S
SegmentFault 最新的问题
小众软件
小众软件
A
Arctic Wolf
酷 壳 – CoolShell
酷 壳 – CoolShell
腾讯CDC
宝玉的分享
宝玉的分享
Last Week in AI
Last Week in AI
G
GRAHAM CLULEY
罗磊的独立博客
T
Tor Project blog
C
Cisco Blogs
美团技术团队
博客园 - Franky
月光博客
月光博客
博客园 - 三生石上(FineUI控件)
T
Threat Research - Cisco Blogs
Cyberwarzone
Cyberwarzone
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
有赞技术团队
有赞技术团队
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Security Latest
Security Latest
博客园 - 司徒正美
Hugging Face - Blog
Hugging Face - Blog
Spread Privacy
Spread Privacy
J
Java Code Geeks
C
CERT Recently Published Vulnerability Notes
大猫的无限游戏
大猫的无限游戏
S
Securelist
The Cloudflare Blog
博客园 - 叶小钗
D
Darknet – Hacking Tools, Hacker News & Cyber Security
阮一峰的网络日志
阮一峰的网络日志
雷峰网
雷峰网
Project Zero
Project Zero

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
Type-Safe API Clients in TypeScript Without a Code Generator
Pavel Espitia · 2026-06-04 · via DEV Community

You call an external API, get back JSON, and write const user = await res.json() as User. TypeScript nods along. Autocomplete works. Everything looks safe.

It is not safe. That as User is a lie you told the compiler. At runtime, res.json() returns any, and the cast tells TypeScript to stop checking. If the API renames a field, adds a null, or returns an error envelope instead of the object you expected, your types still claim everything is fine. The bug surfaces three function calls later, where the stack trace is useless.

The network boundary is exactly where you should trust nothing, and it is the one place most TypeScript code trusts blindly. You can fix this without openapi-typescript-codegen, without a build step, and without committing a 4000-line generated client into your repo. Here is the lightweight approach I use.

The Problem With as

A type assertion is not a check. It is a promise you make to the compiler that you cannot keep.

interface User {
  id: number;
  email: string;
  createdAt: string;
}

async function getUser(id: number): Promise<User> {
  const res = await fetch(`https://api.example.com/users/${id}`);
  return (await res.json()) as User; // a lie
}

Enter fullscreen mode Exit fullscreen mode

Three things go wrong here and none of them are caught:

What happens What TypeScript thinks What you get
API returns { "error": "not found" } User user.email is undefined at runtime
API renames createdAt to created_at User silent undefined, no error until much later
res.json() parses to null User Cannot read property 'id' of null

The cast is structurally identical to writing const user: User = null as any. You have told the type checker to look away at the precise moment you most needed it watching.

The Schema Is the Source of Truth

Instead of declaring a type and asserting reality matches it, declare a schema and verify reality at the boundary. This is "parse, don't validate": you take untyped input and either get a typed value out the other side or a clear failure. There is no in-between state where you have an any pretending to be a User.

I use Zod. Define the shape once, derive the TypeScript type from it.

import { z } from "zod";

const UserSchema = z.object({
  id: z.number().int(),
  email: z.string().email(),
  createdAt: z.coerce.date(),
});

type User = z.infer<typeof UserSchema>;

Enter fullscreen mode Exit fullscreen mode

That z.infer is the whole point. Your runtime validation and your static type come from the same declaration, so they can never drift. There is no generated file to regenerate, no make codegen to forget. The schema is both the validator and the type.

A Generic apiFetch Wrapper

Now wrap fetch so that every response passes through a schema before it reaches your code. The wrapper takes a URL and the schema for the expected body, and returns a value that is genuinely the shape it claims to be.

async function apiFetch<T>(
  url: string,
  schema: z.ZodType<T>,
  init?: RequestInit,
): Promise<T> {
  const res = await fetch(url, init);

  if (!res.ok) {
    throw new ApiError(res.status, `Request failed: ${res.status} ${res.statusText}`);
  }

  let body: unknown;
  try {
    body = await res.json();
  } catch {
    throw new ApiError(res.status, "Response was not valid JSON");
  }

  const parsed = schema.safeParse(body);
  if (!parsed.success) {
    const issues = parsed.error.issues
      .map((i) => `  ${i.path.join(".")}: ${i.message}`)
      .join("\n");
    throw new ApiError(res.status, `Response did not match schema:\n${issues}`);
  }

  return parsed.data;
}

Enter fullscreen mode Exit fullscreen mode

The signature carries the safety. body starts as unknown, the most honest type for "data from the network." It only becomes T after safeParse confirms it. There is no path through this function that returns an unvalidated value typed as T.

Call it with a real public API, the GitHub REST endpoint:

const RepoSchema = z.object({
  full_name: z.string(),
  stargazers_count: z.number().int(),
  language: z.string().nullable(),
  pushed_at: z.coerce.date(),
});

const repo = await apiFetch(
  "https://api.github.com/repos/colinhacks/zod",
  RepoSchema,
);

console.log(repo.full_name, repo.stargazers_count);
//          string         number, both verified at runtime

Enter fullscreen mode Exit fullscreen mode

If GitHub ever changes stargazers_count to a string, you find out at the boundary with a precise message, not in some chart component that silently renders NaN.

Errors as Values, Not Exceptions

Throwing works, but it pushes error handling off into a try/catch somewhere else and erases the error type. A discriminated union makes failure part of the return type, so the compiler forces every caller to handle it.

type Result<T> =
  | { ok: true; data: T }
  | { ok: false; error: ApiError };

class ApiError extends Error {
  constructor(
    public readonly status: number,
    message: string,
  ) {
    super(message);
    this.name = "ApiError";
  }
}

Enter fullscreen mode Exit fullscreen mode

Rewrite the wrapper to return a Result instead of throwing:

async function apiFetch<T>(
  url: string,
  schema: z.ZodType<T>,
  init?: RequestInit,
): Promise<Result<T>> {
  let res: Response;
  try {
    res = await fetch(url, init);
  } catch {
    return { ok: false, error: new ApiError(0, "Network request failed") };
  }

  if (!res.ok) {
    return {
      ok: false,
      error: new ApiError(res.status, `Request failed: ${res.status}`),
    };
  }

  let body: unknown;
  try {
    body = await res.json();
  } catch {
    return { ok: false, error: new ApiError(res.status, "Invalid JSON") };
  }

  const parsed = schema.safeParse(body);
  if (!parsed.success) {
    return {
      ok: false,
      error: new ApiError(res.status, parsed.error.message),
    };
  }

  return { ok: true, data: parsed.data };
}

Enter fullscreen mode Exit fullscreen mode

Now the call site cannot ignore failure. TypeScript narrows data only inside the ok: true branch:

const result = await apiFetch(
  "https://api.github.com/repos/colinhacks/zod",
  RepoSchema,
);

if (!result.ok) {
  console.error(`Failed (${result.error.status}): ${result.error.message}`);
  return;
}

// result.data is User here, and the compiler knows it
console.log(result.data.full_name);

Enter fullscreen mode Exit fullscreen mode

This is the same shape Zod's own safeParse returns, and the same shape Rust's Result and Go's (value, err) give you. Failure stops being an invisible control-flow jump and becomes a value you have to look at.

Typed Query Params

The other place lies creep in is the query string. Hand-building ?status=open&limit=10 with string concatenation invites typos and forgotten encodeURIComponent. Validate params with a schema too, then serialize them in one place.

function buildUrl<T extends z.ZodRawShape>(
  base: string,
  schema: z.ZodObject<T>,
  params: z.infer<z.ZodObject<T>>,
): string {
  const validated = schema.parse(params);
  const url = new URL(base);

  for (const [key, value] of Object.entries(validated)) {
    if (value !== undefined && value !== null) {
      url.searchParams.set(key, String(value));
    }
  }

  return url.toString();
}

Enter fullscreen mode Exit fullscreen mode

Define the allowed params per endpoint, and the call site gets autocomplete plus rejection of anything you did not declare:

const IssueQuerySchema = z.object({
  state: z.enum(["open", "closed", "all"]),
  per_page: z.number().int().min(1).max(100),
});

const url = buildUrl(
  "https://api.github.com/repos/colinhacks/zod/issues",
  IssueQuerySchema,
  { state: "open", per_page: 30 },
);
// passing { state: "opne" } is a compile error, not a runtime 422

Enter fullscreen mode Exit fullscreen mode

URL and URLSearchParams handle the encoding so you never hand-escape a value again.

When a Code Generator IS Worth It

This approach is not a rule against codegen. It is the right default for a specific situation. Here is the line I draw.

Reach for this lightweight approach when Reach for codegen (openapi-typescript, etc.) when
You call a handful of endpoints You consume hundreds of endpoints
The API has no OpenAPI spec, or a bad one The API ships an accurate, maintained spec
You want runtime validation, not just types You only need static types and trust the server
Schemas double as docs and request validators Regenerating on every spec change is acceptable overhead
You control the shapes you care about You need full coverage of a large surface you do not own

Codegen gives you types but usually not runtime validation. Those generated interfaces are still as-casts in disguise: the server can lie and nothing checks. If you want the boundary actually defended, you either pair codegen with a validation layer or you write the schemas yourself. For most apps calling a dozen endpoints, the schemas you write are smaller than the client you would generate, and they earn their keep twice as types and as guards.

What I Learned

  1. A cast is not a check. as User disables exactly the protection you need at the network boundary. Treat it as a code smell anywhere near fetch.

  2. Derive types from schemas, never the reverse. z.infer keeps your runtime validation and static types from drifting, with zero generated files.

  3. Parse at the boundary, trust inside. Untyped data is unknown until a schema proves otherwise. After that, the rest of your code can trust its types completely.

  4. Return errors as values. A Result discriminated union makes the compiler force callers to handle failure instead of letting an exception slip past.

  5. Validate query params too. The query string is part of the boundary. Schema it, then let URL do the encoding.

  6. Use codegen for large specs you do not own, not as a reflex. For most clients, a 30-line wrapper plus a few schemas gives you stronger guarantees than a generated client, because it checks reality at runtime instead of assuming the server keeps its promises.

The whole apiFetch wrapper is under 40 lines and you write it once. Every endpoint after that costs one schema. In exchange, the moment an API breaks its contract, you find out at the exact line where the data entered your program, with a message that tells you which field went wrong. That is the trade the as cast was quietly stealing from you.