Beginner · 10 min
Literal unions
Limit a value to a small set of meaningful choices.
Describe allowed choices
A literal union lists exact allowed values. It catches a misspelled choice in your code. It does not automatically check strings received from outside the program.
type Status = "draft" | "sent";
const status: Status = "sent";
console.log(status);Output
sent
Branch on a known choice
A function can accept a literal union instead of any string. The type describes its callers while the function still uses ordinary JavaScript conditions.
type Size = "small" | "large";
function price(size: Size): number { return size === "large" ? 8 : 5; }
console.log(price("small"));Output
5
Put it into practice
- Read the types and predict the output before running the examples.
- Complete the task, then check your understanding with the practice questions.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Choose a valid status
Assign the allowed value "sent" to "status" and display it. Keep the literal union.
Match the exact spelling of an allowed value.