[TypeScript] Model Alternatives with Discriminated Union Types in TypeScript

使用TypeScript的标记联合类型
本文介绍如何利用TypeScript的标记联合类型定义有限的对象形态集合,并通过实例演示了如何创建一个通用的Result类型,该类型包含成功和失败两种情况。此外,还展示了如何运用这些类型来模拟不同的支付方式。

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))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值