When should you use a generic instead of a union type for a function parameter?
Use a generic when the output type must follow the input type, such as returning the same kind you received. Use a union when the function accepts several kinds and the result does not depend on which one it was.
Explain it simply
Imagine a vending machine. If you put in a coin, a coin-specific snack comes out; put in a note, a different one comes out. The output depends on the input: that calls for a generic, which links the two.
If the machine simply accepts either coin or note and always gives the same snack, a union is enough, because there is no relationship to track.
Example
// Union: result type does not depend on which member arrived
function describe(x: string | number): string {
return `value: ${x}`;
}
// Union loses the link: return type is string | number
function firstUnion(arr: string[] | number[]): string | number | undefined {
return arr[0];
}
// Generic keeps the link
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
const a = first(["x", "y"]); // string | undefined
const b = first([1, 2]); // number | undefinedWhat to say in the interview
"If the return type depends on the argument type, I use a generic so the compiler links them. If the function just accepts a few kinds and returns something fixed, a union is simpler. A type parameter that appears only once is a sign a plain type would do."
Common mistakes
- Adding a type parameter that appears in only one place; it adds noise without linking anything.