TypeScript Union & Literal Types

A value that can be one of several types.

✍️ 3 exercises + code challenge in this lesson
  • Union: let id: string | number;
  • Literal type: an exact value, e.g. "small" | "medium" | "large"
  • Narrowing: check the type with typeof before using type-specific methods.

Key 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

TypeScript
type 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"));
Output
ABC (large)
#42 (small)
Free sign-in required · Google login available

TypeScript Union & Literal Types Practice Exercises

Check what you learned in “TypeScript Union & Literal Types”.

/ 3 solved
Fill in the blank

Name a union type with a type alias.

 Id = string | number;
✓ Correct! Not quite. Try again.
Multiple choice

What is "small" | "large"?

✓ Correct! Not quite. Try again.
Code challenge

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.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

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