Skip to content
All writing

December 26, 2023 · 2 min read

Generics in TypeScript

An introduction to TypeScript generics — what they are, why `any` is a trap, and how `<T>` lets you write code that's both reusable and type-safe.

#typescript

Generics in TypeScript allow you to write functions and classes that can work with a variety of data types while maintaining type safety. They provide a way to create reusable and type-safe components, offering a level of abstraction that promotes code flexibility.

Let's start by looking at a simple example. Consider a function that returns the input it receives:

const num = 1
const str = 'a'

function returnValue(val: any): any {
  return val
}

const numReturn = returnValue(num)
const strReturn = returnValue(str)

While this works, it lacks type safety. The any type means the function can accept any argument, but it doesn't preserve information about the return type. This is where generics come in.

Generics let us create functions and classes that work with different data types while preserving type information:

function returnValue<T>(val: T): T {
  return val
}

const numReturn = returnValue(21)

The T inside the angle brackets <T> represents a type parameter. It acts as a placeholder for the actual type that will be provided when the function is called. For returnValue(21), T is inferred to be number. If you pass a string, T is inferred to be string.

Benefits

  • Type safety. With generics, you can write code that is both flexible and type-safe. The TypeScript compiler catches type-related errors at compile time, providing a safety net that plain JavaScript lacks.
  • Code reusability. Generics allow you to create functions and classes that work with different types without sacrificing reusability — leading to more modular, maintainable code.
  • Functionality abstraction. Generics enable highly abstracted, versatile components. Your code doesn't depend on specific types, making it adaptable.
  • Readability. Type parameters provide meaningful names for the types involved, making code easier to understand.

Conclusion

As you delve deeper into TypeScript, generics become an essential tool for writing robust, reusable, and type-safe code. They enhance the flexibility and maintainability of your projects, making them more scalable and easier to work with in the long run.