How to set types for parameters of multiple, predefined types
Difficulty: 5/10
union types, function overloads, type guards
A TypeScript function can take in parameters of multiple, predefined types using union types.
javascript
Scenario Questions
0-2 years experience
1We have a utility function `formatValue` that should accept either a string or a number and return a string. How would you write its TypeScript signature?
2If you call `formatValue(true)`, what error does TypeScript give and why?
2-5 years experience
1You need to implement a `parseInput` function that can take either a JSON string, a Buffer, or an object conforming to an interface `User`. How would you type its parameter and ensure correct handling inside the function?
2During a code review you notice that a function overloaded to accept `Date | string` is failing when a `null` value is passed. Explain why the current overloads don't cover this case and how you'd fix it.
5-8 years experience
1Our team is building a shared SDK that exposes several functions which accept configuration objects that can be of different shapes (e.g., `HttpConfig` or `WebSocketConfig`). How would you design the type definitions to allow future extensions without breaking existing callers, and what trade‑offs does your approach have?
2We observed a performance regression after adding a generic helper that uses conditional types to narrow parameter types. Explain potential compile‑time vs runtime impacts and how you would mitigate them.
8+ years experience
1The company is migrating a monolith to micro‑services and wants a common TypeScript contract for API request payloads that can be one of many predefined types. Describe how you'd structure the type system (e.g., discriminated unions, branded types) to support versioning, backward compatibility, and tooling integration across teams.
2Several teams have independently added overloads to a core `fetchData` function, leading to conflicting signatures. As a staff engineer, how would you refactor the API to provide a single, extensible type definition while minimizing breaking changes?
Follow-up Questions
What would happen if you later needed to support a boolean type?
How does your approach affect IDE autocomplete for callers?
Can you describe how you’d test that the type guards work as intended?
Sharethis question
Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.