Back

5 Essential TypeScript Tips for Modern Developers

Jun 30, 2025 (11mo ago)

5 Essential TypeScript Tips for Modern Developers

TypeScript is a powerful tool for writing robust and maintainable JavaScript. Here are five tips, each with a code snippet, to help you get the most out of TypeScript in 2025:

1. Use as const for Literal Types

const roles = ["admin", "user", "guest"] as const;
type Role = typeof roles[number]; // "admin" | "user" | "guest"

2. Narrow Types with in and Discriminated Unions

type Shape = { kind: "circle"; radius: number } | { kind: "square"; side: number };
 
function area(shape: Shape) {
  if ("radius" in shape) {
    return Math.PI * shape.radius ** 2;
  }
  return shape.side ** 2;
}

3. Use Utility Types for Cleaner Code

interface User {
  id: string;
  name: string;
  email: string;
}
 
type UserPreview = Pick<User, "id" | "name">;

4. Type-Safe API Responses with Generics

async function fetchJson<T>(url: string): Promise<T> {
  const res = await fetch(url);
  return res.json();
}
 
// Usage:
// const data = await fetchJson<MyType>("/api/data");

5. Avoid any with Unknown

function handleData(data: unknown) {
  if (typeof data === "string") {
    // Now TypeScript knows data is a string
    return data.toUpperCase();
  }
  return null;
}

What are your favorite TypeScript tricks? Share them below!