TypeScript Generics and Advanced Type Operators
Generic type parameters — reusable type relationships
A generic parameter names a type selected for a particular use of a declaration. Using the same parameter in the input and output lets callers retain information instead of losing it to a broad type. The compiler may infer a type argument from inputs, or the caller may supply one explicitly. The implementation must work for all permitted instantiations; a parameter is not a runtime constructor or value. Example output: "draft". Local strict TypeScript 5.8.3 / ES2022 baseline. The type construct itself is erased; the logged value illustrates a checked use, not runtime type validation.
Formal Syntax & Structure
typescript syntaxtypescript
function identity<T>(value: T): T { return value; }Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| T | type parameter | Represents the element type for each invocation. |
Working Example
Example Snippettypescript
function first<T>(items: readonly T[]): T | undefined { return items[0]; }const result: string | undefined = first(["draft", "ready"]);console.log(result);