TypeScript Tips I Wish I Knew Earlier

TypeScript Tips I Wish I Knew Earlier

TypeScript Tips I Wish I Knew Earlier

After years of working with TypeScript, I've collected some tips that have significantly improved my code quality and development experience.

1. Use satisfies for Type Checking

The satisfies operator lets you validate that an expression matches a type without changing the inferred type:

const config = {
  endpoint: '/api',
  timeout: 3000,
} satisfies Config;

2. Discriminated Unions

Instead of optional properties, use discriminated unions for better type safety:

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

function handleResult(result: Result<User>) {
  if (result.success) {
    // TypeScript knows data exists here
    console.log(result.data.name);
  } else {
    // TypeScript knows error exists here
    console.log(result.error);
  }
}

3. Template Literal Types

Create precise string types:

type Route = `/api/${string}`;
type CSSUnit = `${number}${'px' | 'rem' | 'em'}`;

const route: Route = '/api/users'; // OK
const spacing: CSSUnit = '16px'; // OK

4. const Assertions

Preserve literal types with as const:

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

Conclusion

These patterns have made my TypeScript code more robust and self-documenting. Start incorporating them into your projects!