The Complete Guide to TypeScript Generics

SASeed Author·
The Complete Guide to TypeScript Generics

TypeScript generics are one of the most powerful features of the type system. Learn how to write reusable, type-safe code with real-world examples.

Introduction to Generics

Generics allow you to write functions, classes, and interfaces that work with any type while maintaining type safety. They're like variables for types.

Basic Generic Functions

function identity<T>(arg: T): T {
  return arg
}

const num = identity<number>(42)    // T = number
const str = identity<string>('hi') // T = string

Generic Constraints

You can constrain generics to ensure they have specific properties:

interface HasLength {
  length: number
}

function getLength<T extends HasLength>(arg: T): number {
  return arg.length
}

getLength('hello')    // ✓
getLength([1, 2, 3])  // ✓
getLength(42)         // ✗ Error: number has no length

Generic Interfaces and Types

interface ApiResponse<T> {
  data: T
  error: string | null
  status: number
}

type UserResponse = ApiResponse<User>
type PostsResponse = ApiResponse<Post[]>

Real-World Example

Here's a generic hook for data fetching:

function useFetch<T>(url: string) {
  const [data, setData] = useState<T | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetch(url)
      .then(r => r.json())
      .then((d: T) => { setData(d); setLoading(false) })
  }, [url])

  return { data, loading }
}

Conclusion

Generics are essential for writing reusable, type-safe TypeScript code. Mastering them will significantly improve the quality and maintainability of your codebase.

Stay in the loop

Get notified when new posts are published. No spam, unsubscribe anytime.

No spam · Unsubscribe anytime

Leave a Comment

Want to join the conversation?