JS Built-ins
TypeScriptintermediate

Interface β€” Union Type Parser

πŸ“– Usage Example
type Input = string | number
function toString(x: Input): string {
  return typeof x === 'string' ? x : x.toString()
}

A union type A | B accepts either type; narrowing with typeof enables type-specific operations.

Union Types: parseValue

Challenge: Implement parseValue(input) that converts a string to its native JS type:

  • 'true' β†’ true, 'false' β†’ false
  • Numeric strings β†’ number
  • Everything else β†’ string
parseValue('42')     // β†’ 42
parseValue('true')  // β†’ true
πŸ’‘ Hints (1)
  • β€’ Number(str) returns NaN for non-numeric strings β€” isNaN() can detect this.