codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🔷

TypeScript

17 / 60 topics
15Interfaces in TypeScript16Type Aliases17Union Types18Intersection Types19Literal Types20Type Assertions
Tutorials/TypeScript/Union Types
🔷TypeScript

Union Types

Updated 2026-05-15
10 min read

Union Types

Introduction

In TypeScript, union types allow you to combine multiple types into one. This is particularly useful when a variable can hold values of different types. By using union types, you can create more flexible and robust type definitions that accurately represent the diverse data your application might encounter.

Union types are denoted by the pipe (|) symbol between the types you want to combine. For example, if a variable can be either a string or a number, you would define its type as string | number.

Concept

At its core, a union type is a way to express that a value could be one of several types. This feature is especially powerful when dealing with APIs that might return different data types based on certain conditions.

Key Points:

  • Syntax: Use the pipe (|) symbol to separate types.
  • Type Narrowing: TypeScript can infer which type a variable holds at any given point in your code, allowing you to perform operations specific to that type.
  • Null and Undefined: Union types are often used with null or undefined to handle optional values.

Examples

Let's explore some practical examples to understand how union types work and how they can be effectively utilized in TypeScript.

Basic Example: String or Number

Suppose you have a function that accepts either a string or a number as an argument. You can define the parameter type using a union:

TypeScript
1function printValue(value: string | number) {
2console.log(value);
3}
4
5printValue("Hello"); // Works
6printValue(42); // Works
7// printValue(true); // Error: Argument of type 'boolean' is not assignable to parameter of type 'string | number'.

In this example, the value parameter can be either a string or a number. TypeScript ensures that any operations performed on value are valid for both types.

Type Narrowing

TypeScript's type inference and control flow analysis allow you to perform type-specific operations within your code. This is known as type narrowing:

TypeScript
1function formatValue(value: string | number) {
2if (typeof value === "string") {
3 return value.toUpperCase();
4} else {
5 return value.toFixed(2);
6}
7}
8
9console.log(formatValue("hello")); // Outputs: HELLO
10console.log(formatValue(123.456)); // Outputs: 123.46

Here, the typeof check narrows down the type of value, allowing you to call methods specific to strings or numbers.

Union with Null and Undefined

Union types are commonly used with null or undefined to handle optional values:

TypeScript
1function greet(name: string | null) {
2if (name === null) {
3 return "Hello, Guest!";
4}
5return `Hello, ${name}!`;
6}
7
8console.log(greet("Alice")); // Outputs: Hello, Alice!
9console.log(greet(null)); // Outputs: Hello, Guest!

In this example, the greet function accepts a string or null. The check for null ensures that you handle both possible types correctly.

Advanced Example: Union with Objects

Union types can also be used to combine different object types. This is useful when dealing with data structures that might have varying shapes:

TypeScript
1interface Circle {
2kind: "circle";
3radius: number;
4}
5
6interface Square {
7kind: "square";
8sideLength: number;
9}
10
11type Shape = Circle | Square;
12
13function area(shape: Shape): number {
14switch (shape.kind) {
15 case "circle":
16 return Math.PI * shape.radius ** 2;
17 case "square":
18 return shape.sideLength ** 2;
19 default:
20 const _exhaustiveCheck: never = shape;
21 throw new Error("Unknown shape");
22}
23}
24
25const circle: Shape = { kind: "circle", radius: 5 };
26const square: Shape = { kind: "square", sideLength: 10 };
27
28console.log(area(circle)); // Outputs: 78.53981633974483
29console.log(area(square)); // Outputs: 100

In this advanced example, the Shape type is a union of Circle and Square. The area function uses a switch statement to handle different shapes based on their kind property. The _exhaustiveCheck ensures that all possible cases are handled, providing a safeguard against future changes.

What's Next?

Now that you have a solid understanding of union types, the next step is to explore intersection types. Intersection types allow you to combine multiple types into one, requiring that an object satisfy all the combined types. This feature provides another level of type flexibility and precision in your TypeScript applications.

Stay tuned for more advanced topics and keep enhancing your TypeScript skills!


Feel free to experiment with union types in your projects and see how they can make your code more robust and maintainable. Happy coding!


PreviousType AliasesNext Intersection Types

Recommended Gear

Type AliasesIntersection Types