Handle two track identifiers
Before you start this intermediate track
JavaScript objects and functions. The lessons introduce narrowing, unions, and optional properties.
Guided code reading and debugging. Runnable coding challenges are available in JavaScript, Python, and SQL.
Understand it, then try it.
A union allows a value to have more than one possible type. Before calling a method that belongs to just one type, narrow the union with a runtime check. typeof identifies numeric input here. After that branch returns, TypeScript knows the remaining input is a string and allows its uppercase method.
function trackLabel(id: string | number): string { if (typeof id === "number") { return `Track #${id.toFixed(0)}`; } return id.toUpperCase();}console.log(trackLabel("demo"));Use TypeScript 5+ with strict checking and an ES2020 target. Each mission is an independent file. Compile the TypeScript to JavaScript, then run it with Node.js or in a browser console.
Track the values line by line. Predict the result before running this example in your own editor.