TypeScript in Frontend Development: Stop Using `any`
Practical guidance on TypeScript best practices — proper typing for components, services, and utilities — and why eliminating `any` makes your codebase safer.

TypeScript's value proposition is simple: it tells you about bugs before they reach your users. But that promise is only fulfilled if you actually use it properly. The most common way to undermine TypeScript is the `any` type. ## The Problem With `any` `any` is a type-system escape hatch. When you annotate something as `any`, you're telling TypeScript "trust me, I know what I'm doing" — and TypeScript immediately stops checking that variable entirely. ```ts // Bad — TypeScript won't catch any errors here function formatUser(data: any) { return data.nmae; // typo — no error! } ``` ```ts // Good — TypeScript catches the typo immediately type User = { id: string; name: string; email: string }; function formatUser(data: User) { return data.nmae; // Error: Property 'nmae' does not exist on type 'User' } ``` ## Use `unknown` Instead When you genuinely don't know the type — like in a catch block or when parsing external JSON — use `unknown` instead of `any`. It forces you to narrow the type before using it: ```ts function handleError(error: unknown) { if (error instanceof Error) { return error.message; } return "Unexpected error occurred"; } ``` ## Where to Put Types Types should live close to where they're used: - **Shared types** → `src/types/` (used across multiple features) - **Feature types** → `src/features/feature-name/types/` (scoped to one feature) - **Component-local types** → top of the same file ```ts // src/types/user.ts export type UserStatus = "active" | "inactive" | "blocked"; export type User = { id: string; name: string; email: string; status: UserStatus; }; ``` ## Typing Component Props Every React component must have typed props. No exceptions. ```tsx type UserCardProps = { name: string; email: string; role?: string; isActive: boolean; }; export function UserCard({ name, email, role, isActive }: UserCardProps) { return ( <div> <h3>{name}</h3> <p>{email}</p> {role && <span>{role}</span>} <span>{isActive ? "Active" : "Inactive"}</span> </div> ); } ``` ## Typing API Responses Every API call should return a typed value. Don't let raw API responses flow untyped through your app: ```ts type ApiResponse<T> = { data: T; message: string; code: number; }; async function getUsers(): Promise<ApiResponse<User[]>> { const res = await fetch("/api/users"); return res.json(); } ``` TypeScript is only as useful as you make it. When used consistently, it becomes your fastest bug-finding tool — and your best form of documentation.

