Beginner's TypeScript Tutorial (18 exercises)
Problem

Narrowing Down Union Types

Consider this function:

const coerceAmount = (amount: number | { amount: number }) => {};

What this is saying is that what we pass into coerceAmount can be either a number or an object that contains an amount.

Challenge

Your challenge is to write the function so that the tests pass.

There will be some little type errors along the way, but this is an interesting problem to solve.

Transcript

This challenge has a runtime element and a type element. What we've got here is we're saying this coerce amounts thing here, it's saying amount can either be a number or an object containing amounts. That means we can call it with either this here, coerce amounts, or just with a 20 there.

The tests are failing, because it's expecting coerce amount 20 to equal 20, and it's expecting coerce amount, amount 20, to also equal 20. Your job here is to write this function and try and figure out how to work around TypeScript here. You're going to run into some little type errors, and it's going to be interesting, I think, to work out how you handle it.