TypeScript · 3 minute lesson
A union type allows a value to have more than one possible type. This is useful when a function accepts either a text identifier or a numeric identifier. Before using an operation that belongs to only one member of the union, check which kind of value you have.
TypeScript follows control flow to narrow the type inside a branch. A typeof check can establish that a value is a string, making string methods available there. In the other branch, the checker knows which remaining possibility applies.
Prefer checks that reflect real runtime behavior. A type assertion changes what the checker assumes but does not transform or validate the value. Narrowing with an actual condition makes the code explain its decision to both TypeScript and future readers. This becomes especially useful when handling nullable values or differently shaped API results.
Try the example
function formatLessonId(id: string | number): string {
if (typeof id === "string") {
return id.trim().toUpperCase();
}
return `LESSON-${id}`;
}
console.log(formatLessonId(" js-01 "));
console.log(formatLessonId(12));Practice
Extend the accepted type to include null. Add an early check that returns a helpful placeholder for null, then confirm that the string and number branches still receive the correct type information.
Continue learning: Official documentation.