Codectionary / Developer documentation / TypeScript

Generics Basics

Generics let you write reusable functions, classes, and types that work with a variety of types while still preserving type safety - rather than using any and losing that safety, or writing near-duplicate code for each type. A generic type parameter, conventionally named T, acts as a placeholder that gets filled in with a real type each time it is used.

Syntax

function name<T>(param: T): T { }

Examples

A Generic Function

A function that works with any type, while TypeScript still tracks exactly which type was used.

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

const num = identity(42);       // T is inferred as number, returns number
const str = identity("hello");   // T is inferred as string, returns string

// Without generics, you would need "any" (losing type safety)
// or separate functions for each type (losing reusability)

Generics with Arrays

A common, practical use: a function that works with an array of any type.

function getFirstElement<T>(arr: T[]): T | undefined {
  return arr[0];
}

const firstNum = getFirstElement([1, 2, 3]);         // inferred as: number | undefined
const firstName = getFirstElement(["Alice", "Bob"]); // inferred as: string | undefined

Best practices

  • Use generics instead of any when a function or class should work with multiple types while still preserving type safety and autocomplete
  • Let TypeScript infer the generic type argument from the actual arguments passed, rather than always specifying it explicitly (identity<string>("hi") is rarely needed)
  • Use descriptive generic names (TItem, TResponse) instead of just T for complex functions with multiple type parameters, to keep signatures readable
  • Reach for generics specifically when a function's behavior genuinely does not depend on the specific type - if it does, a union type or overloads may fit better

At a glance

Purpose
Static types for JavaScript
File extension
.ts ยท .tsx
Runs in
Compiled to JavaScript
Usually used with
JavaScript and its ecosystem

Specifications & further reading

Related TypeScript documentation