Interview Q&A / Machine Learning

IntermediateQuick answer1 min readUpdated 3 Oct 2026

When should you use a generic instead of a union type for a function parameter?

SHORT ANSWER

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 | undefined

What 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 generic whose parameter appears only once is a sign a union or plain type would do.

Common mistakes

  • Adding a type parameter that appears in only one place; it adds noise without linking anything.

#generics#unions

Related questions

Practise more Machine Learning questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Machine Learning quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.