Codington
0 of 6 problems solved0%

Narrow with an Aliased Union

Sometimes you want a function to accept more than one type but still return a consistent result. Instead of repeating string | number everywhere, you can alias the union type. You can use typeof to narrow to the correct branch and handle each case.

// Alias the union type type StringOrNum = string | number; function toLength(value: StringOrNum): number { if (typeof value === "string") { return value.length; // here it's type string } return value; // here it's type number }

Your Task

  1. Define type Input = string | number.
  2. Implement toNumber(x: Input): number that returns:
  • the value itself when x is a number
  • parseFloat(x) when x is a string (assume valid numeric strings).