TypeScript Union Types

What are Union Types?

Union types allow a variable to hold multiple types.

Use the | symbol to define a union.

Loading...
Output:

Using Union Types in Functions

Loading...
Output:

Type Narrowing

Use conditions to determine the type before using it.

Loading...
Output:

Union with Arrays

Loading...
Output:

Union in Objects

Loading...
Output:

Literal Union Types

Restrict values to specific options.

Loading...
Output:

Full Example

Loading...
Output:

Why Union Types are Important

  • Allow flexible variables
  • Improve type safety
  • Used in APIs
  • Common in real applications

Common Mistakes

  • Not checking types before using values
  • Using too many types
  • Forgetting parentheses in arrays

Practice

Create a function that accepts a number or string and handles them differently.

Loading...
Output:

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic