Generics <T>
Types and functions with a type parameter that work for many types without losing precision.
Example
#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)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
#function name<T>(param: T): T { … }
type Box<T> = { value: T }More examples
#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, []))[1, 2, 3] []
Good practices
#- Type parameter names can be descriptive, e.g.
<TItem>, when there are several of them. A singleTis fine for simple functions. - If a type parameter appears only once in the signature, it probably isn’t needed.
Related entries
#- Generic constraints (extends)Requiring a type parameter to match a specific shape.
- Default type parametersThe value a type parameter takes when it isn’t provided or inferred.
- keyofCreates a union of the key names of a given object type.
- Arrays: number[] and Array<T>Array types, where every element has the same type.
Spotted a mistake or missing an example? Write to us.