How do you declare a function with a generic parameter?
Basic syntax
javascript
function name<T>(arg: T): T {
return arg;
}Tis the generic parameter.- When the function is called, TypeScript substitutes the required type for
Ton its own.
Example 1: a simple generic function
javascript
function identity<T>(value: T): T {
return value;
}
const num = identity(42); // T = number
const str = identity("hello"); // T = stringTypeScript understands that num is number, and str is string.
Example 2: explicit type argument when calling
javascript
function wrapValue<T>(value: T): { data: T } {
return { data: value };
}
const wrapped = wrapValue<string>("text");
// { data: string }Here we manually specified the type <string>, although TypeScript usually does this automatically.
Example 3: multiple generic parameters
javascript
function merge<T, U>(a: T, b: U): T & U {
return Object.assign({}, a, b);
}
const person = merge({ name: "Tim" }, { age: 25 });
// person has the type { name: string; age: number }You can use several generic parameters (<T, U, V, ...>).
Example 4: with a constraint (extends)
javascript
function getLength<T extends { length: number }>(value: T): number {
return value.length;
}
getLength("hello"); // a string has length
getLength([1, 2, 3]); // an array has length
getLength(123); // a number does not have lengthextends constrains which types can be substituted for T.
Example 5: with arrays
javascript
function firstElement<T>(arr: T[]): T {
return arr[0];
}
const first = firstElement([1, 2, 3]); // number
const second = firstElement(["a", "b"]); // stringTypeScript infers the type of the array elements automatically.
Summary
| Syntax | Example | Description |
|---|---|---|
<T> | function foo<T>(x: T): T | One generic parameter |
<T, U> | function bar<T, U>(a: T, b: U) | Several generic parameters |
<T extends SomeType> | function baz<T extends object>(x: T) | A type constraint |
<T = DefaultType> | function qux<T = string>(x?: T) | A default value for the generic |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.