Typed collections
A collection API needs to retain the element type when values are read back.
TypeScript · Function
Generics parameterize functions, classes, interfaces, and types so one declaration can work with many concrete types while preserving relationships between them. Type arguments may be written explicitly or inferred from usage.
Generics introduce type parameters that connect related types across a declaration. A function can use the same parameter for an input and its result, while callers may provide the type argument explicitly or let TypeScript infer it; constraints limit which types are accepted.
function firstElement<Type>(arr: Type[]): Type | undefined| Name | Type | Description |
|---|---|---|
Type | type parameter | A type parameter representing the type captured from the argument. |
arr | Type[] | An array whose elements have the captured type. |
The first element of the input array, or undefined if the array is empty.
function firstElement<Type>(arr: Type[]): Type | undefined {
return arr[0];
}
const first = firstElement([10, 20, 30]);
console.log(first);The compiler infers Type as number, so the returned value is number | undefined.
A collection API needs to retain the element type when values are read back.
A helper transforms or forwards a value without losing its specific type.
A library exposes containers usable with consumer-defined domain types.
An API should accept only types possessing a required property.
A generic type parameter represents a type rather than a runtime value. It lets one declaration preserve relationships between inputs and outputs, such as returning the same element type supplied in an array.
Follow-up: How can the caller avoid writing the type argument? Type argument inference derives it from the value passed to the generic function.
The caller can write an explicit type argument, such as identity<number>(42), or omit it and rely on inference. Inference lets the compiler choose the type parameter from the argument.
Follow-up: When inference is insufficient, what is the direct remedy? Specify the type argument explicitly at the call site.
A constraint restricts a type parameter to types compatible with another type. For example, Type extends Lengthwise permits code to use length while rejecting arguments without that property.
Follow-up: Can a constraint use another type parameter? Yes; the documentation describes constraints whose requirement is expressed in terms of another parameter.
Generic functionsGeneric classesGeneric interfacesType argument inferenceGeneric constraintsDefault type parametersArray<Type>