Skip to main content
← ⚑ JavaScript & the browserΒ·Module C5 Β· Lesson 10
TaskRefactor process(input) per the theory. Define @typedef Input as (number | string | number[]). Narrow with typeof and Array.isArray. Throw TypeError naming the unsupported type for unknown input. Log process(5), process("hi"), process([1,2,3]). Then in try/catch log the error message from process(true).

Capstone: refactor a tangled function with types

250 XP14 min
Theory

What you'll fix

The starter has a single function process(input) that handles three different kinds of input:

  • number β€” return doubled
  • string β€” return uppercased
  • array of numbers β€” return sum

It has no types, no narrowing, no validation. Anything that goes in might explode.

Your job

Apply every C5 idea in one pass:

  1. @typedef for the union type the function actually accepts.
  2. JSDoc @param / @returns on the function.
  3. Narrowing for each branch β€” typeof, Array.isArray.
  4. A clear throw for the unknown-input branch (with the type info in the message).

You'll go from "barely safe spaghetti" to "library-ready function in 12 lines". This is the daily refactor in any non-TS codebase.

πŸ”’

Sign up to start coding

Theory is open to everyone. The interactive editor, live preview, and check are unlocked with a 7-day free trial β€” card required, cancel anytime.

Sign up β€” free trial β†’

First 10 lessons in each track are free. No card needed for those.

← PreviousNext lesson β†’

Get one Python or web tip a day β€” by email

Short, hand-written, no spam. Unsubscribe in one click.