Lesson 3 of 10
Union types and narrowing
- 11 min
- 5 checks
- 3 hints
- Go to task
Goal
A value with more than one type
Explanation
A product ID might arrive as a number like 42 one time and as a string like "ab12" the next. The type string | number says exactly that: the value is one of the two types. This is called a union.
The compiler only lets you do what both types have in common, so id.toUpperCase() is a type error, because numbers have no toUpperCase. It's the same mistake that crashes a JavaScript program the moment a number reaches the function.
The fix is narrowing: inside if (typeof id === "number") the compiler knows id is a number, and in the other branch it knows it's a string. Keep in mind that typeof can't tell an array, null and an object apart, because they're all "object".
Your task
Give the parameter of formatId the type string | number and make it return a string. A string comes back in uppercase after a #, like "#AB12", and a number is padded with zeros to four digits, like "#0042".
Checks
5 checks- No type errors
- formatId accepts a string and a number
- formatId rejects any other type
- formatId("ab12") returns "#AB12" for a string
- formatId(42) returns "#0042" for a number