1.Narrow a union
BeginnerWrite format(value: string | number | boolean): string that returns numbers with two decimals, booleans as "yes" or "no", and strings in upper case. Test it with all three types.
Show hint
Use typeof checks; each branch sees the narrowed type.
Show solution
function format(value: string | number | boolean): string {
if (typeof value === "number") return value.toFixed(2);
if (typeof value === "boolean") return value ? "yes" : "no";
return value.toUpperCase();
}
console.log(format(3), format(true), format("ok"));3.00 yes OK