今日已更新 166 条资讯 | 累计 20138 条内容
关于我们

TypeScript Tips That Actually Matter in Real Projects (including the satisfies operator)

Gavin Cettolo 2026年06月24日 20:57 1 次阅读 来源:Dev.to

Most TypeScript tutorials teach you the language. This article teaches you how to use it. There's a difference. The language has hundreds of features. A real project uses maybe twenty of them regularly, and about eight of them make up the difference between TypeScript that fights you and TypeScript that helps you. These are those eight. Each one comes from a pattern I've seen repeatedly in real codebases: first as an antipattern, then as a realization, then as a habit. The goal isn't to show off advanced type gymnastics. It's to show you the specific things that make your code safer, more readable, and less painful to maintain. TL;DR Most TypeScript pain comes from fighting the type system instead of working with it, any , manual casting, and loose types are the usual culprits. A small set of features, discriminated unions, utility types, satisfies , as const , generics, solve the majority of real-world typing problems. The best TypeScript isn't the most complex. It's the most precise. Table of Contents Tip 1: Use Discriminated Unions Instead of Optional Fields Tip 2: Stop Writing Types Twice with Utility Types Tip 3: Use satisfies to Validate Without Losing Inference Tip 4: Use as const for Literal Types That Don't Drift Tip 5: Write Type Guards Instead of Casting Tip 6: Use Generics to Write Functions Once Tip 7: Use ReturnType and Parameters to Stay in Sync Tip 8: Use unknown Instead of any for External Data Honorable Mentions Final Thoughts Tip 1: Use Discriminated Unions Instead of Optional Fields This is the tip that changes how you model data in TypeScript. Once you see it, you'll spot the antipattern everywhere. The antipattern // ❌ A type that tries to represent multiple states with optional fields interface ApiResponse { data ?: User error ?: string isLoading : boolean } The problem: this type allows impossible states. Nothing stops you from having both data and error set at the same time, or neither set, or isLoading: false with no data and no error . The

本文内容来源于互联网,版权归原作者所有
查看原文