天天看點

[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.

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: "[email protected]"
}

console.log(stringifyPaymentMethod(myPayment))      

繼續閱讀