TypeScript Basics: JavaScript with Types
Union Types and Narrowing
In this lesson you will
- Write union and literal types
- Narrow a union with typeof, equality and in checks
- Use as const and a simple enum alternative
Introduction
Real values are often "this or that": an id that is a number or a string, a status that is one of three words. A union type says a value can be one of several types. It is one of the most useful ideas in TypeScript.
Union types
Join types with |, read as "or".
The catch: you can only use what is safe for all
With a union, TypeScript only lets you use what works for every member:
To use a type-specific feature, narrow the type first, by checking it.
Narrowing with typeof
Inside each branch TypeScript knows the exact type. After the if returns, it also knows the only thing left must be a number.
Quick quiz
What is narrowing?
Other ways to narrow
- Truthiness:
if (value)removesnull,undefined,0and empty text. - Equality:
if (value === null). in: checks whether an object has a property.Array.isArray: tells arrays from single values.
Literal types
A type can be a specific value, not just a kind. Combined with unions, this lets you list the allowed values:
It works like an enum, but it's plain JavaScript strings. Editors can also autocomplete the allowed values.
as const
TypeScript widens let and object values to string. as const freezes a value to its exact literals:
You get one list that serves as both the runtime data and the type, so they cannot drift apart.
Quick quiz
What does the type 'draft' | 'review' | 'published' allow?
Try it yourself
Write a function formatPrice that takes number | string. If it is a string, return it unchanged. If it is a number, return it with a $ and two decimals, like $4.50. The stub has a type error you should fix.
Summary
A | Bis a union: the value is one of the listed types.- With a union you can only use what is safe for every member, until you narrow.
- Narrow with
typeof, equality, truthiness,inandArray.isArray. - Literal unions such as
"draft" | "published"list the allowed values, andas constturns a list into a type.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading