TypeScript
  • Introduction
  • Introduction
    • What is TypeScript?
    • Why TypeScript?
    • Setup
  • Beginner
    • Basic types
      • Primitive types
      • Arrays and tuples
      • Enums
      • Any type
    • Objects
    • Type aliases
    • Interfaces
    • Functions
      • Function signatures
      • Void type
      • Functions as types
    • Union types
    • Type guards
    • Intersection types
    • Nullable types
    • Inference
  • Resources
    • Resources
Powered by GitBook
On this page
  1. Beginner

Union types

Most simple functions only expect arguments of a specific type. For example, square() would expect a number, pluralize() would expect a string and so on. But when you get into situations where the arguemnts are evaluating something like payment methods, things get a bit more complicated.

function processPayment(method) {
    // ...
}

Say we have three different payment methods: Cash, PayPal and CreditCard, how do we type the method argument to allow for all three? By using a union, denoted by the pipe or vertical bar (|) character:

function processPayment(method: Cash | PayPal | CreditCard) {
    // ...
}

We can simplify our example by combining the different payment method types into a named type:

type PaymentMethod = Cash | PayPal | CreditCard;

function processPayment(method: PaymentMethod) {
    // ...
}
PreviousFunctions as typesNextType guards

Last updated 6 years ago