10 TypeScript Tips for Better Code

10 TypeScript Tips for Better Code

Mike Johnson
Mike Johnson
TypeScript Expert
6 min read

Improve your TypeScript skills with these practical tips.

10 TypeScript Tips for Better Code

Level up your TypeScript game with these practical tips.

1. Use Type Inference

Let TypeScript figure out types:

// Bad
const name: string = 'John'

// Good
const name = 'John' // TypeScript knows it's a string

2. Utility Types

Use built-in utility types:

type User = {
  id: number
  name: string
  email: string
}

// Pick specific properties
type UserPreview = Pick<User, 'id' | 'name'>

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

// Make all properties required
type RequiredUser = Required<User>

3. Union Types

type Status = 'idle' | 'loading' | 'success' | 'error'

function handleStatus(status: Status) {
  switch (status) {
    case 'loading':
      return 'Loading...'
    case 'success':
      return 'Done!'
    case 'error':
      return 'Error occurred'
    default:
      return 'Idle'
  }
}

4. Type Guards

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

function process(value: string | number) {
  if (isString(value)) {
    // TypeScript knows value is string here
    return value.toUpperCase()
  }
  return value.toFixed(2)
}

5. Generic Constraints

function getProperty<T, K extends keyof T>(obj: T, key: K) {
  return obj[key]
}

const user = { name: 'John', age: 30 }
const name = getProperty(user, 'name') // ✓
// getProperty(user, 'invalid') // ✗ Error

Type System Flow

graph TD
    A[Source Code] --> B[Type Checker]
    B --> C{Valid?}
    C -->|Yes| D[Compile to JS]
    C -->|No| E[Show Errors]
    D --> F[Runtime]

Summary

TypeScript helps catch errors early and makes code more maintainable. Use these tips to write better TypeScript code!

10 TypeScript Tips for Better Code