Skip to content
dreamcode
dreamcode
Map
TS Unions & Enums Challenge
Section challenge · IntermediateTypeScript
Reward: +50 XP
PROBLEM

TS Unions & Enums Challenge

Write a function parseSpeed(speed) that takes a union type parameter speed: string | number. The function should:

  1. If speed is a number, return it directly.
  2. If speed is a string, parse it using parseFloat(). If the parsed value is not a number (isNaN) or is negative, return -1.
  3. Otherwise, return the parsed number.
Examples
parseSpeed(120)
120
parseSpeed("85.5mph")
85.5
solution.ts
TYPESCRIPT
Saved as you type

Tests

0 of 4 passing
  • number 120 → 120
    parseSpeed(120)
    expected 120
  • string '85.5mph' → 85.5
    parseSpeed("85.5mph")
    expected 85.5
  • invalid string 'fast' → -1
    parseSpeed("fast")
    expected -1
  • negative number -50 → -1
    parseSpeed(-50)
    expected -1
On the line
+50 XP
Pass all 4 tests to claim it.