- Union:
let id: string | number; - Literal type: an exact value, e.g.
"small" | "medium" | "large" - Narrowing: check the type with
typeofbefore using type-specific methods.
TypeScript Union & Literal Types
A value that can be one of several types.
✍️ 3 exercises + code challenge in this lessonKey Takeaways: TypeScript Union & Literal Types
Mastering TypeScript Union & Literal Types helps you write clean and reliable TypeScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
TypeScript Union & Literal Types Code Example
TypeScripttype Size = "small" | "medium" | "large";
function describe(id: string | number, size: Size): string {
if (typeof id === "string") {
return `${id.toUpperCase()} (${size})`;
}
return `#${id.toFixed(0)} (${size})`;
}
console.log(describe("abc", "large"));
console.log(describe(42, "small"));
ABC (large) #42 (small)
TypeScript Union & Literal Types Practice Exercises
Check what you learned in “TypeScript Union & Literal Types”.
Name a union type with a type alias.
Id = string | number;
What is "small" | "large"?
Write format(v: string | number) that returns v.toUpperCase() for strings and v * 2 for numbers. Log format("hi") and format(5) on separate lines.
Free sign-in required · Google login available
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services