TypeScript Course
TypeScript
/
Intermediate

Generic Functions

Definition

Functions that can operate over a variety of types rather than a single one, while still preserving perfect type safety. They use a type variable (usually `<T>`) to capture the type passed by the user.

Explain Like I'm New

A generic function is a template. Imagine a machine that wraps gifts. You don't build a machine for wrapping Books, and a separate machine for wrapping Toys. You build ONE Generic machine, and you tell it 'Whatever type of item goes IN, that exact same type of item comes OUT'.

Real World Example

The `useState<T>()` hook in React. It accepts any type you pass it, and returns an array containing that exact same type.

Common Use Cases

  • •Reusable utility functions
  • •Array manipulation functions like `.map()`

Interactive Example

// BAD: We lose type safety (returns 'any')
function wrapAny(item: any): any {
  return { value: item };
}

// GOOD: The generic <T> links the input type to the output type
function wrapItem<T>(item: T): { value: T } {
  return { value: item };
}

// TS infers T is string. Returns { value: string }
const wrappedString = wrapItem("Alice"); 

// TS infers T is number. Returns { value: number }
const wrappedNumber = wrapItem(100); 

// Multiple generics!
function mergePairs<K, V>(key: K, value: V) {
  return { key, value };
}

Interview Questions

basic

  • What does the `<T>` stand for in Generics?

intermediate

  • Do you always have to explicitly write `<string>` when calling a generic function?

advanced

  • Can a generic function have multiple type variables?

Flash Cards

Question

What does <T> stand for?

Click to reveal answer
Answer

It stands for 'Type'. It is just a placeholder variable name. You could name it `<ItemType>` or `<Thing>`, but `<T>` is the industry standard convention.

Question

Do you always have to write it?

Click to reveal answer
Answer

No! TypeScript has 'Generic Type Inference'. If you call `wrapItem("hello")`, TS automatically figures out that `T` must be `string` based on the argument. You rarely need to write `<string>` manually unless inference fails.