Luan Campina

RPA at Keyrus

Back to writing

TypeScript Tips I Wish I Knew Earlier

After years of TypeScript, these are the patterns that made the biggest difference.

typescriptprogrammingtips

TypeScript isn't just "JavaScript with types." Used well, it transforms how you think about code.

Discriminated unions are magic

type Result<T> = 
  | { success: true; data: T }
  | { success: false; error: string };

function process(r: Result<User>) {
  if (r.success) {
    console.log(r.data); // TypeScript knows this is User
  } else {
    console.log(r.error); // TypeScript knows this is string
  }
}

satisfies keyword

New in TS 4.9, it's a game-changer for type inference:

const config = {
  apiUrl: "https://api.example.com",
  timeout: 5000,
} satisfies Config;
// config.apiUrl is inferred as the literal string, not just 'string'

as const for literals

const COLORS = ["red", "blue", "green"] as const;
type Color = typeof COLORS[number]; // "red" | "blue" | "green"

Template literal types

type EventName = `on${Capitalize<string>}`;
const valid: EventName = "onClick"; // ✓
const invalid: EventName = "click"; // ✗

My favorite utility types

  • Partial<T> — all properties optional
  • Required<T> — all properties required
  • Pick<T, K> — select specific properties
  • Omit<T, K> — exclude specific properties
  • Record<K, V> — create object type

TypeScript's type system is Turing-complete. Use that power wisely.