TypeScript Tips and Tricks for Better Code

March 5, 2024

TypeScript Tips and Tricks for Better Code

TypeScript has become the go-to choice for building scalable JavaScript applications. Here are some tips and tricks to help you write better TypeScript code.

1. Use Type Inference

TypeScript is smart—let it infer types when it can:

// Good: TypeScript infers the type
const user = { name: "John", age: 30 };

// Unnecessary: You don't need to specify the type here
const user: { name: string; age: number } = { name: "John", age: 30 };

2. Leverage Union Types

Union types make your code more flexible and type-safe:

type Status = "loading" | "success" | "error";

function handleStatus(status: Status) {
  // TypeScript knows status can only be one of these three values
}

3. Use Utility Types

TypeScript provides built-in utility types:

interface User {
  id: string;
  name: string;
  email: string;
}

// Make all properties optional
type PartialUser = Partial<User>;

// Pick specific properties
type UserPreview = Pick<User, "name" | "email">;

4. Create Custom Type Guards

Type guards help TypeScript narrow down types:

function isString(value: unknown): value is string {
  return typeof value === "string";
}

function process(value: unknown) {
  if (isString(value)) {
    // TypeScript knows value is a string here
    console.log(value.toUpperCase());
  }
}

5. Use Const Assertions

Const assertions create more specific types:

// Type: { name: string; age: number }
const user = { name: "John", age: 30 };

// Type: { readonly name: "John"; readonly age: 30 }
const userConst = { name: "John", age: 30 } as const;

Conclusion

These tips will help you write more robust TypeScript code. Remember, the goal is to leverage TypeScript's type system to catch errors early and make your code more maintainable.