TypeScript Reference ยท Generics
Multiple type parameters in TypeScript
Reference for TypeScript generics with several type parameters: relate inputs and outputs, merge objects, map keys to values and know the inference limits.
A generic declaration can have as many type parameters as it needs, separated by commas: <T, U, K>. Each parameter is inferred or supplied independently, and the signature can relate them to each other: the output type derived from the input type, one parameter constrained by another, or two inputs combined into one result.
Use more than one parameter when the types genuinely vary independently. If two parameters always have to be equal, use a single one.
function zip<A, B>(as: A[], bs: B[]): [A, B][] { return as.map((a, i) => [a, bs[i]!]); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
function f<A, B, C extends A | B>(a: A, b: B): C; interface Mapper<In, Out = In> { (value: In): Out } class Cache<K, V> { /* ... */ }
| Part | Description |
|---|---|
<A, B> |
Independent type parameters. Each is inferred from its own positions. |
C extends A |
One parameter constrained by an earlier (or later) one. |
= Default |
Optional fallback; defaulted parameters must come last. |
Errors: passing the wrong number of explicit type arguments is TS2558 ("Expected N type arguments, but got M"). There is no way to supply only some of them, unless the rest have defaults.
Usage notes
- Every parameter should earn its place. Each should appear in at least two positions or tie the input to the output. Extra parameters make signatures harder to read and calls harder to infer.
- Order is a design choice. Put the parameters callers are most likely to write first, and defaulted ones last. Conventional names:
Kfor keys,Vfor values,Tfor the main type,Rfor results. - Related parameters can be written as one.
<T, K extends keyof T>tiesKtoT;<T, U extends T>allowsUto be a subtype ofT. - Inference is per parameter. If one of them can be inferred and the other cannot, the second becomes
unknown. Restructure so every parameter has an argument position, or use currying (see Higher-order generic functions). - Intersections from merging can produce
neverfor conflicting property types ({ a: string } & { a: number }hasa: never). - Mapped helpers such as
Record<K, V>andMap<K, V>use the same idea in the standard library. - Avoid unused parameters. A parameter that is never used cannot be inferred and silently turns into
unknown.