zoukankan      html  css  js  c++  java
  • [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
      }
    }
  • 相关阅读:
    0722
    SGU
    预测一下吧
    0625
    0624
    0610
    0607
    0604
    poj2455Secret Milking Machine【二分 + 最大流】
    BZOJ3489: A simple rmq problem
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13773524.html
Copyright © 2011-2022 走看看