How do you declare a generic type parameter on a function, and how do you explicitly specify it when calling?
Short answer
Add ` ` (or any name) right after the function name to declare a type parameter, then use T within the parameter and return types; you can let TypeScript infer T from the arguments, or explicitly specify it in angle brackets at the call site.
Advertisement
AModel answer
Add `<T>` (or any name) right after the function name to declare a type parameter, then use T within the parameter and return types; you can let TypeScript infer T from the arguments, or explicitly specify it in angle brackets at the call site.
function wrapInArray<T>(value: T): T[] {
return [value];
}
wrapInArray('hi'); // inferred: string[]
wrapInArray<number>(5); // explicit: number[]Real-world example
Explicitly specifying a generic type argument when the compiler can't infer it confidently from the call alone, like an empty array literal.
Likely follow-ups
- When would you actually NEED to explicitly specify a generic type argument, rather than relying on inference?
Related topics