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

推荐订阅源

P
Palo Alto Networks Blog
大猫的无限游戏
大猫的无限游戏
Martin Fowler
Martin Fowler
GbyAI
GbyAI
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
量子位
T
The Blog of Author Tim Ferriss
Y
Y Combinator Blog
Microsoft Azure Blog
Microsoft Azure Blog
C
CERT Recently Published Vulnerability Notes
Recent Announcements
Recent Announcements
A
About on SuperTechFans
aimingoo的专栏
aimingoo的专栏
P
Privacy International News Feed
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
博客园 - 叶小钗
L
Lohrmann on Cybersecurity
G
GRAHAM CLULEY
T
The Exploit Database - CXSecurity.com
Hugging Face - Blog
Hugging Face - Blog
P
Proofpoint News Feed
NISL@THU
NISL@THU
博客园 - Franky
C
Cybersecurity and Infrastructure Security Agency CISA
The Register - Security
The Register - Security
M
MIT News - Artificial intelligence
Know Your Adversary
Know Your Adversary
A
Arctic Wolf
F
Full Disclosure
T
Threat Research - Cisco Blogs
P
Privacy & Cybersecurity Law Blog
The Hacker News
The Hacker News
博客园 - 【当耐特】
D
Docker
T
Tailwind CSS Blog
S
SegmentFault 最新的问题
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Jina AI
Jina AI
Help Net Security
Help Net Security
V
Visual Studio Blog
小众软件
小众软件
B
Blog
Vercel News
Vercel News
云风的 BLOG
云风的 BLOG
N
News and Events Feed by Topic
Forbes - Security
Forbes - Security
N
Netflix TechBlog - Medium
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
C
Cisco Blogs
Security Archives - TechRepublic
Security Archives - TechRepublic

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
React + TypeScript Best Practices in 2025: What Actually Matters
Harshdeep Singh · 2026-06-03 · via DEV Community

You open a new React project, add TypeScript, and immediately hit Stack Overflow for how to type your first prop. The first answer says use interface. The second says type. The third is a six-paragraph thread about why one is semantically superior to the other. You close the tab and just write any to get on with your life.

Sound familiar? TypeScript in React has a reputation problem. Not because it's hard — it's genuinely great once it clicks — but because the community has generated a staggering volume of contradictory, context-free advice. Every dev tool tutorial starts with TypeScript. Every linting config bans any. Every PR reviewer has a hot take on generics.

This guide cuts through that. I'm not going to cover every TypeScript feature or every React pattern. What I'm going to do is share the specific conventions I use in production React + TypeScript apps in 2025 — the things that have made codebases genuinely easier to work in, not just theoretically safer.

What this guide is NOT

Before we get into it, let me set expectations clearly:

  • Not a TypeScript basics tutorial. I'm assuming you know what a type is, what an interface is, and that string !== String.
  • Not exhaustive. TypeScript has dozens of utility types, conditional types, template literal types, and more. I'm not covering all of them — just the ones I reach for constantly.
  • Not framework-neutral. This is specifically about TypeScript in React apps. Some of these patterns won't apply to a Node.js CLI or a library.
  • Not about configuration. Strict mode settings, tsconfig targets, module resolution — another article for another day.

What this guide IS is opinionated. I'm going to tell you what I think the right call is in most situations, and why. You'll disagree with some of it. That's fine.

Typing Props the Right Way

Let's start here because it's where every React + TypeScript journey begins, and where a lot of the confusion lives.

Interface vs. Type Alias

Here's my rule: use interface for component props, type for everything else.

Why? Interfaces have declaration merging, which can occasionally bite you in unexpected ways, but they also produce cleaner error messages and feel more natural for describing object shapes. They're also what the React community defaults to, so your code will look familiar to anyone joining your team.

// Good — interface for component props
interface ButtonProps {
  label: string;
  onClick: () => void;
  variant?: "primary" | "secondary" | "ghost";
  disabled?: boolean;
}

// Good — type alias for unions and computed shapes
type ButtonVariant = "primary" | "secondary" | "ghost";
type Theme = "light" | "dark";

Enter fullscreen mode Exit fullscreen mode

You'll see guides that say "always use type" or "always use interface." Honestly? Consistency matters more than which one you pick. Pick a rule and stick to it across your codebase.

Required vs. Optional Props

Default to required. Make something optional only when it genuinely has a sensible default or when it's truly not needed in many use cases.

This is the inverse of what a lot of developers do. They add ? to everything to make TypeScript stop complaining, and then their components have fifteen optional props where most of them are actually always passed. That erases the value of having types at all.

// Bad — over-optionalized
interface CardProps {
  title?: string;
  description?: string;
  imageUrl?: string;
  href?: string;
}

// Good — be explicit about what's truly optional
interface CardProps {
  title: string;
  description: string;
  imageUrl?: string; // genuinely optional — card can work without an image
  href?: string;    // optional — sometimes cards aren't clickable
}

Enter fullscreen mode Exit fullscreen mode

Extending HTML Element Props

This is one of the most useful patterns in React + TypeScript, and it's underused. When you're building a component that wraps an HTML element, extend that element's props so your component accepts all the native attributes automatically.

// Without this pattern — you have to manually add every HTML attribute
interface ButtonProps {
  label: string;
  onClick: () => void;
  // what about type="submit"? aria-label? data-testid? className?
  // you'll spend forever adding these one by one
}

// With this pattern — extend React's built-in types
interface ButtonProps extends React.ButtonHTMLAttributes {
  label: string;
  variant?: "primary" | "secondary";
  // ...and you automatically get onClick, type, aria-*, data-*, className, etc.
}

const Button = ({ label, variant = "primary", ...rest }: ButtonProps) => {
  return (

      {label}

  );
};

Enter fullscreen mode Exit fullscreen mode

The ...rest spread pattern combined with extended HTML props is one of those things that once you start using, you can't go back. Your components become instantly more composable and you stop maintaining a manual list of passthrough props.

Custom Hooks with TypeScript

Custom hooks are where TypeScript really earns its keep, because hooks often manage complex state and return multiple values. If your hook's return type is just inferred as any[], you've lost all the benefit.

Typing Return Values Explicitly

Always define the return type of custom hooks explicitly. Don't rely on inference here — it breaks down the moment your hook has multiple return paths or conditional logic.

// Bad — inferred return type is unreliable
function useUser(id: string) {
  const [user, setUser] = useState(null); // typed as null
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // ...fetch logic

  return { user, loading, error }; // TypeScript infers this poorly
}

// Good — define the return interface explicitly
interface User {
  id: string;
  name: string;
  email: string;
}

interface UseUserResult {
  user: User | null;
  loading: boolean;
  error: string | null;
}

function useUser(id: string): UseUserResult {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // ...fetch logic

  return { user, loading, error };
}

Enter fullscreen mode Exit fullscreen mode

Now when you destructure this hook in a component, every field is typed correctly, and you get autocomplete without having to remember what the hook returns.

Generics for Reusable Hooks

Okay so here's where hooks get really powerful. If you're building a reusable data-fetching hook, generics let you make it work with any shape of data without losing type safety.

interface FetchResult {
  data: T | null;
  loading: boolean;
  error: string | null;
}

function useFetch(url: string): FetchResult {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    let cancelled = false;

    fetch(url)
      .then((res) => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json() as Promise;
      })
      .then((d) => {
        if (!cancelled) {
          setData(d);
          setLoading(false);
        }
      })
      .catch((err: Error) => {
        if (!cancelled) {
          setError(err.message);
          setLoading(false);
        }
      });

    return () => { cancelled = true; };
  }, [url]);

  return { data, loading, error };
}

// Usage — TypeScript knows exactly what data is
const { data, loading, error } = useFetch("/api/user/123");
// data is typed as User | null — not unknown, not any

Enter fullscreen mode Exit fullscreen mode

The T propagates through the entire hook. That's the magic. You call useFetch<User> once at the call site, and TypeScript figures out the rest.

Generic Components

Generics in components are the thing that trips up most mid-level React developers. They look intimidating. They have funny angle-bracket syntax. But once you understand when to reach for them, they save you from maintaining three slightly-different versions of the same component.

When to Use Generic Components

Reach for generics when your component works with data of a variable shape, but still needs to be type-safe. A list component, a select dropdown, a data table — these are classic candidates.

// Without generics — you end up with separate UserList, ProjectList, etc.
// or you use any[] and lose type safety

// With generics — one component that works for any data shape
interface ListProps {
  items: T[];
  renderItem: (item: T, index: number) => React.ReactNode;
  keyExtractor: (item: T) => string;
  emptyMessage?: string;
}

function List({ items, renderItem, keyExtractor, emptyMessage = "No items" }: ListProps) {
  if (items.length === 0) {
    return 
{emptyMessage}
;
  }

  return (


      {items.map((item, index) => (
        - {renderItem(item, index)}
      ))}


  );
}

// Usage — TypeScript infers T from the items array
 u.id}  // TypeScript knows u is a User
  renderItem={(u) => }
/>

Enter fullscreen mode Exit fullscreen mode

Notice that you don't even need to write <List<User>> at the call site — TypeScript infers T = User from the items prop. That's inference doing its job.

One thing to watch: in .tsx files, the compiler can confuse <T> with a JSX tag. If you get a parse error, either add a constraint (<T extends object>) or use a comma (<T,>) to disambiguate.

Discriminated Unions for State

Here's the thing that's changed how I think about React state more than anything else: replacing boolean flags with discriminated union types. This single pattern eliminates entire categories of bugs.

The Boolean Flag Problem

You've seen this component. You've written this component.

// The boolean flag trap
interface FormState {
  isLoading: boolean;
  isSuccess: boolean;
  isError: boolean;
  errorMessage?: string;
  data?: SubmitResult;
}

// Nothing stops you from setting isLoading: true AND isSuccess: true simultaneously
// That's an impossible state — but TypeScript can't catch it
const state: FormState = {
  isLoading: true,
  isSuccess: true, // ← this should be impossible
  isError: false,
};

Enter fullscreen mode Exit fullscreen mode

When you have three booleans representing what should be a single sequential state, you have 2³ = 8 possible combinations, but only 4 of them are actually valid. TypeScript can't protect you from the invalid ones.

The Discriminated Union Fix

// Model the actual states that can exist
type FormState =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: SubmitResult }
  | { status: "error"; errorMessage: string };

// Now the impossible states are literally unrepresentable
const state: FormState = { status: "idle" };

// And in your component, TypeScript narrows types automatically
function FormFeedback({ state }: { state: FormState }) {
  if (state.status === "loading") {
    return ;
  }

  if (state.status === "error") {
    // TypeScript knows state.errorMessage exists here
    return ;
  }

  if (state.status === "success") {
    // TypeScript knows state.data exists here
    return ;
  }

  return null; // idle
}

Enter fullscreen mode Exit fullscreen mode

The key is the status discriminant property. When you narrow on state.status === "error", TypeScript automatically knows which variant of the union you're in, and which other fields are available.

This pattern is especially powerful in data-fetching scenarios, form submission flows, and anywhere you have a multi-step process. Start reaching for it instead of isLoading / isError / isSuccess and your state management will become dramatically cleaner.

Taming any

Let me be direct: any is a code smell, but it's not always your fault. Sometimes you're working with a library that has poor types, an API that returns unpredictable shapes, or legacy code you don't own. The goal isn't to never use any — it's to reach for better tools first.

Use unknown Instead of any for External Data

unknown is the type-safe cousin of any. It says "I don't know what this is yet" instead of "pretend this is whatever I need it to be." You can't do anything with an unknown value without first narrowing it with a type guard.

// Bad — any lets you do anything, including wrong things
async function fetchData(url: string): Promise {
  const res = await fetch(url);
  return res.json();
}

const data = await fetchData("/api/user");
data.doesNotExist.boom; // TypeScript is fine with this. Your app is not.

// Good — unknown forces you to validate before using
async function fetchData(url: string): Promise {
  const res = await fetch(url);
  return res.json();
}

function isUser(value: unknown): value is User {
  return (
    typeof value === "object" &&
    value !== null &&
    "id" in value &&
    "name" in value &&
    typeof (value as User).id === "string"
  );
}

const data = await fetchData("/api/user");
if (isUser(data)) {
  // TypeScript now knows data is User
  console.log(data.name);
}

Enter fullscreen mode Exit fullscreen mode

Type Guards Are Your Friends

The value is User return type in the example above is a type guard. It's a function that tells TypeScript "if this returns true, the value is of type T in the branches that follow." This is how you move from unknown territory into properly typed territory without resorting to any.

// Reusable type guard pattern
function isNonNull(value: T | null | undefined): value is T {
  return value !== null && value !== undefined;
}

const items: (User | null)[] = [user1, null, user2, null];
const validUsers = items.filter(isNonNull); // typed as User[], not (User | null)[]

Enter fullscreen mode Exit fullscreen mode

When never Is the Right Answer

never is the type that can't exist. It's useful for exhaustiveness checks — making sure you've handled every case in a union.

type Shape = "circle" | "square" | "triangle";

function getArea(shape: Shape, size: number): number {
  switch (shape) {
    case "circle":
      return Math.PI * size * size;
    case "square":
      return size * size;
    case "triangle":
      return (size * size) / 2;
    default:
      // If you add "hexagon" to the Shape union and forget to handle it here,
      // TypeScript will throw a compile error on this line
      const _exhaustiveCheck: never = shape;
      throw new Error(`Unhandled shape: ${_exhaustiveCheck}`);
  }
}

Enter fullscreen mode Exit fullscreen mode

This pattern scales beautifully with discriminated unions. Add a new status to your state type, and every switch statement that wasn't updated will fail at compile time. That's exactly the kind of safety net TypeScript is supposed to provide.

Before vs. After: TypeScript Patterns

Here's a quick-reference table of the common before/after shifts. These are the six patterns I most often see in code review that a bit of TypeScript discipline cleans up immediately.

  Pattern
Without TypeScript Discipline
With TypeScript Discipline

Prop typing
props: any or no types at all
interface ButtonProps extends React.ButtonHTMLAttributes&lt;HTMLButtonElement&gt;

Optional props
Everything is ? to avoid errors
Only truly optional fields are optional; defaults handled by destructuring

Loading/error state
isLoading: boolean, isError: boolean, isSuccess: boolean
Discriminated union: { status: "idle" | "loading" | "success" | "error" }

External API data
const data: any = await fetch(...).then(r =&gt; r.json())
const data: unknown + type guard before use

Reusable list
Separate UserList, ProjectList components with duplicated logic
One generic List&lt;T&gt; component with typed renderItem and keyExtractor

Hook return type
Inferred — breaks on multiple return paths, confusing autocomplete
Explicit interface UseXxxResult { ... } as the return type annotation

Enter fullscreen mode Exit fullscreen mode




Module Structure for a TypeScript React Project

Okay, one more thing worth getting right from the start: where files live. A consistent folder structure does more for long-term maintainability than almost any TypeScript pattern. Here's the structure I use and recommend for mid-to-large React + TypeScript apps in 2025.

src/
├── app/ # Next.js App Router pages (or pages/ for older setup)
│ ├── layout.tsx
│ ├── page.tsx
│ └── blog/
│ └── [slug]/
│ └── page.tsx

├── components/ # Shared UI components
│ ├── Button/
│ │ ├── Button.tsx # Component
│ │ ├── Button.types.ts # Interface / type exports
│ │ ├── Button.styles.ts# Styled components or CSS module
│ │ └── index.ts # Re-export for clean imports
│ └── List/
│ └── ...

├── hooks/ # Custom hooks
│ ├── useFetch.ts
│ ├── useLocalStorage.ts
│ └── useDebounce.ts

├── lib/ # Utilities, helpers, non-UI logic
│ ├── api.ts # Fetch wrappers
│ ├── formatters.ts # Date, currency, string helpers
│ └── validators.ts # Type guards and runtime validation

├── types/ # Shared TypeScript types
│ ├── api.ts # API response shapes
│ ├── models.ts # Domain model interfaces (User, Post, etc.)
│ └── index.ts # Re-exports

├── context/ # React context providers
│ └── ThemeContext.tsx

└── styles/ # Global styles, theme tokens
└── globals.css

A few rules I enforce in this structure:

  • Co-locate component types. Each component folder has its own .types.ts file. Don't dump all types into a single global types.ts — that file becomes a graveyard.
  • The types/ directory is for shared domain types only. API response shapes, database models, shared interfaces that more than one component needs. Not component-specific props.
  • Barrel files are useful but dangerous. An index.ts in each component folder is fine. A single barrel for your entire components/ directory will cause circular dependency nightmares in larger apps.
  • Hooks go in hooks/, not co-located with components. This is a deliberate choice against the "co-locate everything" philosophy. In my experience, hooks get reused across features, and burying them inside a component folder makes them harder to find and share.

TL;DR

  • Use interface for component props, type for everything else — pick a rule and apply it consistently. Default to required props; only mark things optional when they genuinely are.
  • Extend HTML element props using React.ButtonHTMLAttributes<HTMLButtonElement> and friends — this gets you all native attributes for free and makes components composable with ...rest.
  • Always annotate custom hook return types explicitly — define a UseXxxResult interface and return it. Don't trust inference when there's conditional logic involved.
  • Use discriminated unions instead of boolean flags for anything with multiple states — { status: "idle" | "loading" | "success" | "error" } is safer, clearer, and catches impossible states at compile time.
  • Replace any with unknown at API boundaries — then validate with type guards before use. Save never for exhaustiveness checks in switch statements.
  • Structure your modules intentionally — co-locate component types, put shared domain types in types/, hooks in hooks/, and use barrel files per component folder (not globally).