Back to all posts
TypeScriptJavaScriptProgrammingFrontend

TypeScript Best Practices for 2025: Writing Scalable, Type-Safe Code

April 2, 20258 min read
TypeScript Best Practices for 2025: Writing Scalable, Type-Safe Code

TypeScript Best Practices for 2025: Writing Scalable, Type-Safe Code

TypeScript has become an indispensable technology for web development. As applications grow in complexity, writing clean, maintainable, and type-safe code requires leveraging modern TypeScript features effectively.


1. Enable Strict Mode in tsconfig.json

Always enable "strict": true in your project configuration. Strict type checking catches subtle runtime bugs early during development:

{
  "compilerOptions": {
    "target": "ES2022",
    "moduleResolution": "bundler",
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noUncheckedIndexedAccess": true
  }
}

2. Leverage Discriminated Unions for State Management

Discriminated unions allow TypeScript to narrow complex application states deterministically using a common literal field:

type LoadingState = { status: "idle" | "loading" };
type SuccessState<T> = { status: "success"; data: T };
type ErrorState = { status: "error"; error: Error };

type AsyncData<T> = LoadingState | SuccessState<T> | ErrorState;

function renderUserUI(state: AsyncData<User>) {
  switch (state.status) {
    case "loading":
      return <Spinner />;
    case "success":
      return <UserProfile user={state.data} />; // TypeScript knows state.data exists!
    case "error":
      return <ErrorMessage message={state.error.message} />;
  }
}

3. Avoid any: Use unknown for Unverified Inputs

The any type disables type checking completely, leading to hidden runtime bugs. Instead, use unknown when dealing with external API responses or dynamic inputs, then narrow with Zod or type guards:

import { z } from "zod";

const UserSchema = z.object({
  id: z.string(),
  name: z.string(),
  email: z.string().email(),
});

type User = z.infer<typeof UserSchema>;

async function fetchUser(id: string): Promise<User> {
  const response = await fetch(`/api/users/${id}`);
  const rawData: unknown = await response.json();
  
  // Safe runtime validation and compile-time inference
  return UserSchema.parse(rawData);
}

4. Master Utility Types

TypeScript comes with powerful built-in utility types that eliminate code duplication:

interface UserProfile {
  id: string;
  name: string;
  email: string;
  avatarUrl: string;
  createdAt: Date;
}

// 1. Omit unneeded fields for creation payloads
type CreateUserPayload = Omit<UserProfile, "id" | "createdAt">;

// 2. Pick only fields required for card views
type UserCardInfo = Pick<UserProfile, "name" | "avatarUrl">;

// 3. Make all fields optional for update operations
type UpdateUserPayload = Partial<CreateUserPayload>;

5. Use Generic Constraints Wisely

When writing reusable functions, constrain generic parameters to ensure required properties exist:

function getEntityId<T extends { id: string | number }>(entity: T): T["id"] {
  return entity.id;
}

Conclusion

Adopting these TypeScript best practices improves code predictability, provides superior IDE autocomplete, and prevents entire categories of production bugs before code is ever shipped.

Daniel Chukwudubem

Daniel Chukwudubem

Software engineer passionate about building great products.