Skip to content

Generics

Generics allow you to create code that works over a variety of types while maintaining type safety. They're like templates that can work with different types without losing the specific type information.

We won't use generics a lot in this course, and we we do, it will only be the most basic form.

Basic Example

Consider JavaScript's "identity function" that simply returns whatever it receives:

ts
function identity(arg) {
  return arg;
}

const n = identity(123);
const s = identity("hello");

In TypeScript, we can use generics to preserve the type information:

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

const n = identity(123);      // TypeScript knows n is number
const s = identity("hello");  // TypeScript knows s is string

The <T> syntax tells TypeScript that T is a type parameter. When you call the function, TypeScript automatically infers what T should be based on the argument you pass.

⚠️ Don't confuse TypeScript generics with C++ templates!

While they look similar with angle brackets (<T>), TypeScript generics are purely compile-time constructs that get erased during transpilation. They don't create separate compiled versions for each type like C++ templates do. TypeScript generics are just a way to preserve type information during development.

Why Use Generics?

Without generics, you'd need to either:

  • Use any (losing type safety)
  • Create separate functions for each type
  • Use union types (less specific)

Generics give you the best of both worlds: type safety and flexibility.

External Resources