Shailesh Parmar’s Post

Most React bugs aren't logic errors. They're state shape errors. ⚠️ The type allowed it. And nobody caught it until production. 𝗛𝗲𝗿𝗲'𝘀 𝘄𝗵𝗮𝘁 𝗺𝗼𝘀𝘁 𝗧𝘆𝗽𝗲𝗦𝗰𝗿𝗶𝗽𝘁 𝘀𝘁𝗮𝘁𝗲 𝗹𝗼𝗼𝗸𝘀 𝗹𝗶𝗸𝗲: interface RequestState { isLoading: boolean; data?: User; error?: string; } This type allows impossible states: ● isLoading: true AND data: User at the same time ● error: "failed" AND data: User at the same time ● isLoading: false with no data and no error — what just happened? setState({ isLoading: false, data: undefined, error: undefined }); UI shows nothing. No loading. No error. Just a blank screen. Your UI is now guessing which state is real. 𝗗𝗶𝘀𝗰𝗿𝗶𝗺𝗶𝗻𝗮𝘁𝗲𝗱 𝘂𝗻𝗶𝗼𝗻𝘀 𝗲𝗹𝗶𝗺𝗶𝗻𝗮𝘁𝗲 𝘁𝗵𝗲 𝗴𝘂𝗲𝘀𝘀𝗶𝗻𝗴: type RequestState = | { status: 'idle' } | { status: 'loading' } | { status: 'success'; data: User } | { status: 'error'; error: string } Now impossible states are actually impossible. data only exists on success. error only exists on error. TypeScript enforces it — not your runtime checks. 𝗨𝘀𝗶𝗻𝗴 𝗶𝘁 𝗶𝗻 𝗮 𝗰𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁: switch (state.status) { case 'loading': return <Spinner />; case 'error': return <Error message={state.error} />; case 'success': return <Dashboard data={state.data} />; default: return null; } No optional chaining. No data?.user?.name. No undefined checks. The compiler already knows what exists at each branch. ⚠️ Boolean flags scale poorly. State machines don't. 🎯 𝗧𝗵𝗲 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆 The goal of TypeScript isn't to describe what your data looks like. It's to make wrong states unrepresentable. 💬 What's a bug you hit because your state allowed something impossible? Drop it below. 👇 #TypeScript #SoftwareEngineering #WebDev #FrontendEngineering #ReactJS

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories