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, )
};
}
return {
success: false,
error: "Invalid number format"
};
} const result = tryParseInt(""); 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))

[TypeScript] Model Alternatives with Discriminated Union Types in TypeScript的更多相关文章

  1. [TypeScript] Union Types and Type Aliases in TypeScript

    Sometimes we want our function arguments to be able to accept more than 1 type; e.g. a string or an ...

  2. 投票通过,PHP 8 确认引入 Union Types 2.0

    关于是否要在 PHP 8 中引入 Union Types 的投票已于近日结束,投票结果显示有 61 名 PHP 开发组成员投了赞成票,5 名投了反对票. 还留意到鸟哥在投票中投了反对票~) 因此根据投 ...

  3. [TypeScript] Type check JavaScript files using JSDoc and Typescript 2.5

    Typescript 2.5 adds JSDoc type assertion support for javascript file via ts-check service. First of ...

  4. [TypeScript] Query Properties with keyof and Lookup Types in TypeScript

    The keyof operator produces a union type of all known, public property names of a given type. You ca ...

  5. [TypeScript] Transform Existing Types Using Mapped Types in TypeScript

    Mapped types are a powerful and unique feature of TypeScript's type system. They allow you to create ...

  6. [TypeScript] Represent Non-Primitive Types with TypeScript’s object Type

    ypeScript 2.2 introduced the object, a type that represents any non-primitive type. It can be used t ...

  7. [TypeScript] Using Assertion to Convert Types in TypeScript

    Sometimes the compiler needs help figuring out a type. In this lesson we learn how to help out the c ...

  8. [TypeScript] Understand lookup types in TypeScript

    Lookup types, introduced in TypeScript 2.1, allow us to dynamically create types based on the proper ...

  9. Java中的Union Types和Intersection Types

    前言 Union Type和Intersection Type都是将多个类型结合起来的一个等价的"类型",它们并非是实际存在的类型. Union Type Union type(联 ...

随机推荐

  1. [NOIP2010提高组]引水入城

    题目:洛谷P1514.Vijos P1777.codevs1066. 题目大意:有一个$n×m$的矩阵,每个点都有一个高度,可以在第一行的任意点建立蓄水厂.现在要把水输到最后一行的所有点上,规定水只能 ...

  2. rsync---远程数据同步工具

    rsync命令是一个远程数据同步工具,可通过LAN/WAN快速同步多台主机间的文件.rsync使用所谓的“rsync算法”来使本地和远程两个主机之间的文件达到同步,这个算法只传送两个文件的不同部分,而 ...

  3. Android如何从外部跳进App

    博客出自:http://blog.csdn.net/liuxian13183,转载注明出处! All Rights Reserved ! 这个问题解决了两天时间,因为网上没有完整的解决方案,解决后分享 ...

  4. [转] C# HttpWebRequest 绝技

    c# HttpWebRequest与HttpWebResponse绝技    阅读原文 如果你想做一些,抓取,或者是自动获取的功能,那么就跟我一起来学习一下Http请求吧.本文章会对Http请求时的G ...

  5. 已知二叉树的中序序列为DBGEAFC,后序序列为DGEBFCA,给出相应的二叉树

    面对这种问题时我们该怎么解决? 今天写数据结构题.发现了一道总是碰见问题的题在这里我写了一种求解方法我自己称它为分层递归求解. 第一步通过观察我们知道后序遍历时最后一个是根节点A 在中序序列中A的左边 ...

  6. 14.idea右键单击没有 svn选项处理办法

    转自:http://www.cnblogs.com/xiohao/p/5044213.html 问题一: IntelliJ IDEA打开带SVN信息的项目不显示SVN信息,项目右键SVN以及图标还有C ...

  7. 【实用篇】获取Android通讯录中联系人信息

    第一步,在Main.xml布局文件中声明一个Button控件,布局文件代码如下: <LinearLayout xmlns:android="http://schemas.android ...

  8. POSTGRESQL NO TABLE

    POSTGRESQL EXTENDING SQL GRIGGER PROCEDURAL

  9. Bundles软件

    Bundle 称为:软件集 或 打包捆绑软件(软件束) Bundle就是一组包含了文件集,软件包或许可程序产品的软件,它们组合在一起为了实现一个特定的功能     快速来列出系统bundle软件 sm ...

  10. GPT模式下ghost系统 安装方法

    GPT模式下ghost系统 安装方法 1.UEFI进入PE 2.使用diskgenius 软件 分区,选择GPT方式分区 3.使用CGI ghost 系统 文件到安装盘 4.UEFI修复:软件为 BC ...