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) {
    // ...
}

Last updated