← Back to blog

TypeScript on the frontend: common mistakes and how to avoid them

2026-06-10

TypeScript on the Frontend: Common Mistakes and How to Avoid Them

TypeScript has become the de facto standard for frontend development, especially in React and Next.js ecosystems. While it brings tremendous value through static typing, many developers fall into recurring traps that undermine its benefits. This post covers the most common mistakes I encounter in production codebases and provides practical solutions to write more robust, maintainable TypeScript.

1. The Any Trap and Insufficient Typing

The most dangerous practice in TypeScript is reaching for any when types become complex. This effectively disables the type checker and propagates untyped values throughout your application.

Consider this problematic pattern common in React components:

// Bad: Using any for API responses
function UserProfile({ userId }: { userId: string }) {
  const [user, setUser] = useState<any>(null);
  
  useEffect(() => {
    fetch(`/api/users/${userId}`)
      .then(res => res.json())
      .then(data => setUser(data));
  }, [userId]);
  
  return <div>{user?.name}</div>; // No type safety, typos pass silently
}

Instead, define explicit interfaces and use them consistently:

// Good: Explicit typing with interfaces
interface User {
  id: string;
  name: string;
  email: string;
  role: 'admin' | 'editor' | 'viewer';
  createdAt: string;
}

interface ApiResponse<T> {
  data: T;
  meta: {
    total: number;
    page: number;
  };
}

function UserProfile({ userId }: { userId: string }) {
  const [user, setUser] = useState<User | null>(null);
  
  useEffect(() => {
    fetch(`/api/users/${userId}`)
      .then(res => res.json())
      .then((response: ApiResponse<User>) => setUser(response.data));
  }, [userId]);
  
  // TypeScript now catches: user?.neme (typo) or user?.role === 'superadmin'
  return <div>{user?.name}</div>;
}

Configure your tsconfig.json to prevent accidental any usage:

{
  "compilerOptions": {
    "noImplicitAny": true,
    "strict": true,
    "noUncheckedIndexedAccess": true
  }
}

2. Incorrect Event Handler Types in React

React's synthetic event system requires specific types that many developers approximate incorrectly. Using generic DOM types instead of React's specialized types leads to missing properties and incorrect autocompletion.

// Bad: Using generic DOM types
function FormComponent() {
  const handleSubmit = (e: Event) => { // Wrong: missing React-specific properties
    e.preventDefault(); // Error: Property 'preventDefault' does not exist on 'Event'
    // ...
  };
  
  const handleChange = (e: Event) => {
    const value = e.target.value; // Error: Property 'value' does not exist
  };
  
  return (
    <form onSubmit={handleSubmit}>
      <input onChange={handleChange} />
    </form>
  );
}

Use React's specialized event types:

// Good: Proper React event types
import { FormEvent, ChangeEvent, MouseEvent, KeyboardEvent } from 'react';

function FormComponent() {
  const [email, setEmail] = useState<string>('');
  
  const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    // Full access to form methods, currentTarget for form data
    const formData = new FormData(e.currentTarget);
  };
  
  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    setEmail(e.target.value); // Properly typed as string
  };
  
  const handleClick = (e: MouseEvent<HTMLButtonElement>) => {
    // Access to button-specific properties
    const isDisabled = e.currentTarget.disabled;
  };
  
  const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      // Handle enter specifically
    }
  };
  
  return (
    <form onSubmit={handleSubmit}>
      <input 
        type="email" 
        value={email}
        onChange={handleChange}
        onKeyDown={handleKeyDown}
      />
      <button onClick={handleClick}>Submit</button>
    </form>
  );
}

3. Prop Drilling with Poor Type Definition

Passing props through multiple component layers without proper typing creates maintenance nightmares. In Next.js applications with server and client components, this becomes particularly problematic.

// Bad: Inline prop types with duplication
function Parent() {
  const user = { id: '1', name: 'Alice', email: 'alice@example.com' };
  return <Child user={user} />;
}

function Child({ user }: { user: any }) { // any again!
  return <Grandchild user={user} />;
}

function Grandchild({ user }: { user: { name: string } }) { // Incomplete type!
  return <div>{user.email}</div>; // Runtime error: email not in type
}

Centralize types and use composition patterns:

// Good: Centralized types with proper composition
// types/user.ts
export interface User {
  id: string;
  name: string;
  email: string;
  avatarUrl?: string;
  preferences: UserPreferences;
}

export interface UserPreferences {
  theme: 'light' | 'dark' | 'system';
  notifications: boolean;
}

// components/UserCard.tsx
import { User } from '@/types/user';

interface UserCardProps {
  user: Pick<User, 'name' | 'email' | 'avatarUrl'>;
  onEdit: (userId: string) => void;
}

export function UserCard({ user, onEdit }: UserCardProps) {
  return (
    <div>
      <img src={user.avatarUrl} alt={user.name} />
      <h3>{user.name}</h3>
      <p>{user.email}</p>
      <button onClick={() => onEdit(user.id)}>Edit</button>
    </div>
  );
}

// components/UserProfile.tsx
interface UserProfileProps {
  userId: string;
}

export async function UserProfile({ userId }: UserProfileProps) {
  // Next.js Server Component with typed fetch
  const user = await fetchUser(userId); // Returns Promise<User>
  
  return (
    <UserCard 
      user={user} 
      onEdit={(id) => redirect(`/users/${id}/edit`)}
    />
  );
}

4. Misusing Type Assertions and Non-Null Assertions

The as keyword and ! operator are escape hatches that bypass type checking. Overusing them indicates design problems that should be addressed.

// Bad: Excessive type assertions
function processData(response: unknown) {
  const data = response as { users: any[] }; // Dangerous assumption
  const firstUser = data.users[0]!;
  const name = firstUser!.name!; // Multiple layers of unsafe assumptions
  
  return name as string; // Redundant and unsafe
}

Use type guards and proper narrowing:

// Good: Runtime type validation with type guards
function isUser(value: unknown): value is User {
  return (
    typeof value === 'object' &&
    value !== null &&
    'id' in value &&
    'name' in value &&
    'email' in value &&
    typeof (value as Record<string, unknown>).id === 'string' &&
    typeof (value as Record<string, unknown>).name === 'string'
  );
}

function isUsersArray(value: unknown): value is User[] {
  return Array.isArray(value) && value.every(isUser);
}

interface ApiError {
  error: string;
  code: number;
}

function isApiError(value: unknown): value is ApiError {
  return (
    typeof value === 'object' &&
    value !== null &&
    'error' in value &&
    'code' in value
  );
}

// Proper handling with discriminated unions
type ApiResult<T> = 
  | { success: true; data: T }
  | { success: false; error: ApiError };

async function fetchUsers(): Promise<ApiResult<User[]>> {
  const response = await fetch('/api/users');
  const json = await response.json();
  
  if (!response.ok && isApiError(json)) {
    return { success: false, error: json };
  }
  
  if (isUsersArray(json)) {
    return { success: true, data: json };
  }
  
  return { 
    success: false, 
    error: { error: 'Invalid response format', code: 500 } 
  };
}

5. Ignoring Generic Constraints in Reusable Components

Generic components without proper constraints lose type information, forcing consumers to use type assertions or accept any types.

// Bad: Generics without constraints
function DataTable<T>({ 
  data, 
  columns 
}: { 
  data: T[]; 
  columns: { key: string; title: string }[] 
}) {
  return (
    <table>
      <tbody>
        {data.map((row, i) => (
          <tr key={i}>
            {columns.map(col => (
              // row[col.key as keyof T] requires assertion, no autocomplete
              <td>{String(row[col.key as keyof T])}</td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

Constrain generics with keyof for full type safety:

// Good: Constrained generics with path autocompletion
interface Column<T, K extends keyof T = keyof T> {
  key: K;
  title: string;
  render?: (value: T[K], row: T) => React.ReactNode;
}

function DataTable<T extends Record<string, unknown>>({ 
  data, 
  columns 
}: { 
  data: T[]; 
  columns: Column<T>[] 
}) {
  return (
    <table>
      <thead>
        <tr>
          {columns.map(col => (
            <th key={String(col.key)}>{col.title}</th>
          ))}
        </tr>
      </thead>
      <tbody>
        {data.map((row, i) => (
          <tr key={i}>
            {columns.map(col => {
              const value = row[col.key]; // Fully typed, no assertion needed
              return (
                <td key={String(col.key)}>
                  {col.render 
                    ? col.render(value, row) 
                    : String(value)
                  }
                </td>
              );
            })}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

// Usage with full type inference and autocomplete
interface Product {
  id: string;
  name: string;
  price: number;
  inStock: boolean;
}

<DataTable<Product>
  data={products}
  columns={[
    { key: 'name', title: 'Product Name' }, // Autocomplete suggests: id, name, price, inStock
    { 
      key: 'price', 
      title: 'Price',
      render: (price) => `$${price.toFixed(2)}` // price correctly typed as number
    },
    {
      key: 'inStock',
      title: 'Availability',
      render: (inStock) => inStock ? 'Yes' : 'No' // boolean, not any
    }
  ]}
/>

6. Next.js-Specific Typing Oversights

Next.js App Router introduces async server components and new patterns that require specific TypeScript considerations.

// Bad: Missing types for Next.js page props
export default function Page({ params, searchParams }) {
  // params and searchParams are implicitly any
  const { id } = params;
  return <div>{id}</div>;
}

Use Next.js built-in types:

// Good: Properly typed Next.js pages
import { Metadata } from 'next';

// For dynamic route segments
interface PageProps {
  params: Promise<{ id: string }>; // Next.js 15+: params is async
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}

export async function generateMetadata({ 
  params 
}: PageProps): Promise<Metadata> {
  const { id } = await params;
  const product = await fetchProduct(id);
  
  return {
    title: product.name,
    description: product.description,
  };
}

export default async function ProductPage({ params, searchParams }: PageProps) {
  const { id } = await params;
  const query = await searchParams;
  
  const relatedOnly = query.related === 'true';
  const product = await fetchProduct(id, { relatedOnly });
  
  return <ProductDetail product={product} />;
}

// For API routes with NextRequest
import { NextRequest, NextResponse } from 'next/server';

interface UpdateBody {
  name?: string;
  price?: number;
}

export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  const body: unknown = await request.json();
  
  // Validate with type guard before processing
  if (!isValidUpdateBody(body)) {
    return NextResponse.json(
      { error: 'Invalid request body' }, 
      { status: 400 }
    );
  }
  
  const updated = await updateProduct(id, body);
  return NextResponse.json(updated);
}

7. State Management Type Leakage

Global state solutions like Zustand, Redux, or Context often suffer from poorly typed stores that propagate any through selectors.

// Bad: Untyped Zustand store
const useStore = create((set) => ({
  bears: 0,
  increase: (by) => set((state) => ({ bears: state.bears + by })),
}));

// usage: by is implicitly any, no autocomplete
function BearCounter() {
  const bears = useStore((state) => state.bears); // bears: any
  const increase = useStore((state) => state.increase);
  return <button onClick={() => increase(1)}>{bears}</button>;
}

Type the store comprehensively:

// Good: Fully typed Zustand store with slices
interface BearSlice {
  bears: number;
  increase: (by: number) => void;
  decrease: (by: number) => void;
}

interface FishSlice {
  fishes: number;
  addFish: () => void;
}

type Store = BearSlice & FishSlice;

const useStore = create<Store>()((set) => ({
  bears: 0,
  increase: (by) => set((state) => ({ bears: state.bears + by })),
  decrease: (by) => set((state) => ({ bears: state.bears - by })),
  fishes: 0,
  addFish: () => set((state) => ({ fishes: state.fishes + 1 })),
}));

// Type-safe selectors with derived state
function BearCounter() {
  // Optional: use typed selectors for reusability
  const bears = useStore((state) => state.bears); // number
  const increase = useStore((state) => state.increase); // (by: number) => void
  const fishBearRatio = useStore((state) => 
    state.fishes > 0 ? state.bears / state.fishes : 0
  ); // number, computed safely
  
  return (
    <button onClick={() => increase(1)}>
      Bears: {bears} (ratio: {fishBearRatio.toFixed(2)})
    </button>
  );
}

Conclusion

Effective TypeScript on the frontend requires discipline beyond basic syntax. The mistakes covered here, recurring in production React and Next.js codebases, share a common theme: types are treated as documentation rather than as executable contracts. By enforcing strict compiler settings, validating data at boundaries, constraining generics properly, and using framework-specific types, you transform TypeScript from a verbose JavaScript into a genuine reliability tool.

The investment in proper typing pays dividends in refactoring confidence, onboarding speed, and bug prevention. Start by auditing your codebase for any usage and unvalidated external data, then apply the patterns demonstrated here systematically.