Generics <T>

Types and functions with a type parameter that work for many types without losing precision.

On this page

Example

#
TypeScript
function first<T>(items: T[]): T | undefined {
  return items[0]
}

const name = first(['Emma', 'Jack'])
// const name: string | undefined
const course = first([{ title: 'HTML', modules: 11 }])
// const course: { title: string; modules: number } | undefined

console.log(name?.toUpperCase())
console.log(course?.modules)
Result
EMMA
11

Definition and usage

#

A generic is a type with a parameter, written in angle brackets: <T>. It lets you write a function, class, or type once and use it with different data types, while keeping full type information.

Without generics, a function that returns the first element of an array would have to return any or unknown. With the generic function first<T>(items: T[]): T | undefined, the compiler knows that for an array of strings the result is a string, and for an array of courses it’s a course object.

Most of the time the type parameter is inferred from the arguments, so you don’t need to provide it. You write it explicitly when it can’t be inferred, for example useState<string | null>(null).

Syntax

#
Syntax
function name<T>(param: T): T { … }
type Box<T> = { value: T }

More examples

#
A generic API response type
TypeScript
type ApiResponse<T> = { ok: true; data: T } | { ok: false; error: string }

function unwrap<T>(response: ApiResponse<T>, fallback: T): T {
  return response.ok ? response.data : fallback
}

const levels: ApiResponse<number[]> = { ok: true, data: [1, 2, 3] }
const failed: ApiResponse<number[]> = { ok: false, error: 'timeout' }

console.log(unwrap(levels, []))
console.log(unwrap(failed, []))
Result
[1, 2, 3]
[]

Good practices

#
  • Type parameter names can be descriptive, e.g. <TItem>, when there are several of them. A single T is fine for simple functions.
  • If a type parameter appears only once in the signature, it probably isn’t needed.

Related entries

#

Spotted a mistake or missing an example? Write to us.