HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to TypeScriptBasic TypesUnion & Literal TypesInterfacesTyped FunctionsArrays & TuplesGenerics & Enums
REFERENCE
📖 Overview
🖥️ Basics & Output
🏷️ Types
📐 Interface & Type Alias
🧩 Function
📋 Array & Object Types
🚀 Next
TypeScript›Union & Literal Types

Union & Literal Types

Giving a variable multiple types (|) and allowing only specific values (literal).

Simple enough for a 5-year-old to understand

Union type ( | )

With |, you state that a variable can be one of several types.

Example code
1
let identity: number | string;
Can be a number OR text.
VariableCan be a number OR text.
2
identity = 42;
Number — valid.
VariableNumber — valid.
3
console.log(identity);
42
Output / Input42
4
identity = "A42";
Text — also valid.
VariableText — also valid.
5
console.log(identity);
A42
Output / InputA42
VariableOutput / Input

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.What does number | string mean?

About this topic

A union type states that a value can be one of several types. This is the natural way to express JavaScript's actual behavior: a function can accept text or a number, an API response can be a success or an error.

The power of unions emerges when combined with TYPE NARROWING. TypeScript tracks which type you are dealing with inside an if block; when you check with typeof, you can safely use that type's methods inside the block.

Literal types are even more precise: they state that a variable can only take specific TEXT values. You declare that a status field can only be "pending", "approved" or "cancelled"; a typo becomes a compilation error. This eliminates much of the need for enums.

What you will learn

  • Defining a union type
  • Narrowing types with typeof and in
  • Literal types
  • Building discriminated unions
  • Catching missing cases with never
  • Intersection types

When to use?

A discriminated union is the safest way to model API responses: every state has a tag field, and TypeScript looks at that tag to know which fields exist. If you try to access the error field in a success state, the compiler blocks it.

A literal union is lighter than an enum for fixed option sets: it generates no extra code, works directly with text, and goes smoothly with JSON.

Common mistakes

Wrong

function format(value: string | number) {
  return value.toFixed(2);
}

In a union type, you can only access properties found in ALL members; toFixed does not exist on text. The compiler gives "Property 'toFixed' does not exist on type 'string | number'". You must narrow it first.

Correct

function format(value: string | number) {
  if (typeof value === "number") return value.toFixed(2);
  return value;
}

Wrong

let status: string = "pending";
status = "pending";

Since the type is string, any text is valid and a typo goes unnoticed; the comparison silently fails further down the code. A literal union catches this error at compile time.

Correct

let status: "beklemede" | "onaylandi" | "iptal" = "beklemede";
status = "onaylandi";

Wrong

type Result =
  | { ok: true; data: string }
  | { ok: false; error: string };

function show(r: Result) {
  return r.data;
}

In a discriminated union, you cannot access the field without checking the tag; data only exists when ok is true. The compiler gives "Property 'data' does not exist on type Result" — and this is precisely the protection you want.

Correct

function show(r: Result) {
  if (r.ok) return r.data;
  return r.error;
}

Frequently asked questions

Should I use an enum or a literal union?

In most cases, a literal union. Enums generate code at runtime, are incompatible with JSON, and add an unnecessary layer. Unions, on the other hand, give the same safety with zero runtime cost and work directly with text.

How does type narrowing work?

TypeScript tracks code flow: when it sees a typeof, in, instanceof or a tag comparison, it narrows the type inside that block. This flow analysis stops at the function boundary — if you pass a narrowed value to another function, the narrowing is lost.

How do I catch a missing case?

In the final branch of a switch, you assign the value to a variable of type never. When you add a new member to the union, that assignment gives a compilation error and tells you which switch you need to update. This pattern is invaluable in growing state machines.

Summary

A union type states that a value can be one of several types, and its power emerges with type narrowing. Literal unions are a lightweight and more compatible alternative to enums; discriminated unions are the safest way to model API responses.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code