Skip to main content

Multiple generics

Basic syntax

javascript
function example<T, U>(arg1: T, arg2: U): [T, U] { return [arg1, arg2]; }
  • T and U are two generic parameters (you can add more: <T, U, V, ...>).
  • Each type parameter is inferred independently.
  • TypeScript substitutes the matching types automatically when calling.

Example 1: a pair of values of different types

javascript
function pair<T, U>(first: T, second: U): [T, U] { return [first, second]; } const a = pair("age", 25); // T = string, U = number // result: [string, number]

Type inference happens automatically: T became string, U became number.


Example 2: merging objects

javascript
function merge<T, U>(a: T, b: U): T & U { return Object.assign({}, a, b); } const user = merge({ name: "Tim" }, { age: 25 }); // user: { name: string; age: number }

Here T and U describe the types of both arguments, and the return type is their intersection (&).


Example 3: using constraints (extends)

javascript
function combine<T extends object, U extends object>(obj1: T, obj2: U): T & U { return { ...obj1, ...obj2 }; } combine({ id: 1 }, { name: "Alex" }); // OK combine({ id: 1 }, 42); // Error - number does not fit object

Constraints (extends) let you control which types are allowed.


Example 4: dependent parameters

javascript
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; } const user = { name: "Tim", age: 25 }; const name = getProperty(user, "name"); // T = { name: string; age: number }, K = "name" // name has type string

Here K depends on T: it is a key of the object T. TypeScript knows that key must be a valid key of that object.


Example 5: with a default type

javascript
function wrap<T, U = string>(value: T, note?: U): { value: T; note: U } { return { value, note: note as U }; } wrap(123); // T = number, U = string (default) wrap(true, "flagged"); // T = boolean, U = string

Generic parameters can have default values when TypeScript cannot infer them.


Summary

FeatureExampleWhat it does
Two parameters<T, U>Different types for different arguments
Constraints<T extends object, U extends object>Restricts the types
Dependency<T, K extends keyof T>One parameter depends on another
Default type<T, U = string>Used when not specified explicitly

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.