zoukankan      html  css  js  c++  java
  • [TypeScript] Model Alternatives with Discriminated Union Types in TypeScript

    TypeScript’s discriminated union types (aka tagged union types) allow you to model a finite set of alternative object shapes in the type system. The compiler helps you introduce fewer bugs by only exposing properties that are known to be safe to access at a given location. This lesson shows you how to define a generic Result<T> type with a success case and a failure case. It also illustrates how you could use discriminated unions to model various payment methods.

    In the example, we make Result type restrict the return type, if success, it should return value, if not, return error prop.

    type Result<T> =
      | { success: true; value: T }
      | { success: false; error: string };
    
    function tryParseInt(text: string): Result<number> {
      if (/^-?d+$/.test(text)) {
        return {
            success: true,
            value: parseInt(text, 10)
        };
      }
      return {
        success: false,
        error: "Invalid number format"
      };
    }
    
    const result = tryParseInt("42");
    
    if (result.success) {
     result; // refer to success case only
     console.log(result.value)
    } else {
      result; // refer to error case only
    }
    interface Cash {
    kind: "cash";
    }
    
    interface PayPal {
    kind: "paypal";
    email: string;
    }
    
    interface CreditCard {
    kind: "creditcard";
    cardNumber: string;
    securityCode: string;
    }
    
    type PaymentMethod = Cash | PayPal | CreditCard;
    
    function stringifyPaymentMethod(method: PaymentMethod): string {
    switch (method.kind) {
        case "cash":
            return "Cash";
        case "paypal":
            return `PayPal (${method.email})`;
        case "creditcard":
            return "Credit Card";
    }
    }
    
    const myPayment = {
    kind: "paypal",
    email: "typescript@egghead.io"
    }
    
    console.log(stringifyPaymentMethod(myPayment))
  • 相关阅读:
    搜索条件中的模式匹配,及包含关键字条件匹配
    Makefile用法,详细到让人吐。
    循序渐进实现仿QQ界面(三):界面调色与控件自绘
    VC 多线程编程
    用UDL快速生成一个数据库连接字符串。
    VC CMarkup所有方法说明
    VC判断控件是否按钮。
    学习笔记(一)
    libvirt0.8.2安装(方法一)
    centos中kvm网桥的设置
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7827395.html
Copyright © 2011-2022 走看看