Suggest an editImprove this articleRefine the answer for “How do you declare a function with a generic parameter?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)A function with a generic parameter is declared as `function name<T>(arg: T): T { return arg; }`, where `T` is a **generic parameter**. **Key point:** when the function is called, TypeScript substitutes the required type for `T` on its own, though it can also be specified explicitly (`identity<string>("text")`).Shown above the full answer for quick recall.Answer (EN)Image### Basic syntax ```javascript function name<T>(arg: T): T { return arg; } ``` - `T` is the **generic parameter**. - When the function is called, TypeScript **substitutes** the required type for `T` on 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 = string ``` TypeScript 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 length ``` `extends` 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"]); // string ``` TypeScript 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 |For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.