0 of 5 problems solved0%
2 of 5

Format ID Union

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.

Your Task

  • Create type Id = string | number.
  • Implement formatId(id: Id): string that returns:
    • "NUM: <id>" if id is a number
    • "STR: <id>" if id is a string.