Union types and narrowing
string | number means "either a string or a number" - a union of two types.
A parameter typed id: string | number could genuinely be handed either one,
so before doing anything type-specific with it, you need to check which type
you actually got. That check is called a type guard , and the simplest one
is typeof:
if (typeof id === 'number') {
// id is treated as a number here
}
Inside that if, the value is narrowed to just number - outside it, or in
an else, it's still the other option. This is the pattern that makes a union
type useful rather than just a wider hole to fall through.
Your task: write formatId(id) - if id is already a string, return it
unchanged; if it's a number, return it as a string prefixed with #.
You'll practice:
Declaring a union type with |
Narrowing a union with a typeof check
Show a hint
Show solution
Related reading: Unions, Literals & Narrowing - One of Several Shapes →
Previous Next