[Typescript] Discriminated (Tagged) Unions

Discriminated (Tagged) Unions means that for two or more similar types, we have one common prop which can differentiate individual.

 

interface Order {
  id: string;
  amount: number;
  currency: string;
}

interface Stripe {
  type: "stripe";
  card: string;
  cvc: string;
}

interface PayPal {
  type: "paypal";
  email: string;
}

type CheckoutCard = Order & Stripe;
type CheckoutPayPal = Order & PayPal;

const order: Order = {
  id: "xj28s",
  amount: 100,
  currency: "USD"
};

const orderCard: CheckoutCard = {
  ...order,
  type: "stripe",
  card: "1000 2000 3000 4000",
  cvc: "123"
};

const orderPayPal: CheckoutPayPal = {
  ...order,
  type: "paypal",
  email: "abc@def.com"
};

 

Usage:

type Payload = CheckoutCard | CheckoutPayPal;

function checkout(payload: Payload) {
  if (payload.type === "stripe") {
    // is CheckoutCard type
  }

  if (payload.type === "paypal") {
    // is CheckoutPaypal
  }
}

 

posted @ 2020-10-06 15:27  Zhentiw  阅读(279)  评论(0)    收藏  举报