A union like string | number lets a function accept multiple representations of the same concept. Inside the function, narrow with typeof and convert to a single output type. This keeps the public API flexible while ensuring a consistent, predictable return value.
type Key = string | number;
function toKeyString(k: Key): string {
if (typeof k === "number") {
return String(k);
}
return k;
}Favor a single union-typed parameter over many overloads when the behavior is identical for each variant.
type Id = string | number.formatId(id: Id): string that returns:
"NUM: <id>" if id is a number"STR: <id>" if id is a string.