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. 监控mysqld服务

    #!/bin/bash #监控mysqld服务 #telnet 192.168.122.171 3306 | grep Connected | wc -l #远程检查 #num=`netstat -n ...

  2. ids for this class must be manually assigned before calling save():Xxx

    把Xxx.hbm.xml主键生成策略改成identity

  3. C#+ArcGIS Engine 获取地图中选中的要素

    转自 C#+ArcGIS Engine 获取地图中选中的要素 C#+ArcGIS Engine 获取地图中选中的要素 提供一种简单遍历获取地图中选中要素的方法,代码如下: List<IFeatu ...

  4. C# Winform利用POST传值方式模拟表单提交数据(Winform与网页交互)

    其原理是,利用winfrom模拟表单提交数据.将要提交的參数提交给网页,网页运行代码.得到数据.然后Winform程序将网页的全部源码读取下来.这样就达到windows应用程序和web应用程序之间传參 ...

  5. [Recompose] Merge RxJS Button Event Streams to Build a React Counter Component

    Combining input streams then using scan to track the results is a common scenario when coding with s ...

  6. Linux Unix shell 编程指南学习笔记(第五部分)

    第二十五章 深入讨论 << 当shell 看到 << 的时候,它知道下一个词是一个分界符.该分界符后面的内容都被当做输入,直到shell又看到该分界符(位于单独的一行).比方: ...

  7. ubuntu12.04更新软件源时出现校验和不符

    在运行update命令之后.出现系统校验和不符.网上找了一些方法,最后在大神的帮助下最终攻克了! ! 1.更改 /etc/apt/apt.conf.d/00aptitude 文件,在最后一行增加: A ...

  8. nodeJs学习路线

    转载自:http://blog.fens.me/nodejs-roadmap/ 前言 用Nodejs已经1年有余,陆陆续续写了48篇关于Nodejs的博客文章,用过的包有上百个. 和全部人一样,我也从 ...

  9. 八款常用的 Python GUI 开发框架推荐

    作为Python开发者,你迟早都会用到图形用户界面来开发应用.本文将推荐一些 Python GUI 框架,希望对你有所帮助,如果你有其他更好的选择,欢迎在评论区留言. Python 的 UI 开发工具 ...

  10. thinkphp里面使用原生php

    thinkphp里面使用原生php Php代码可以和标签在模板文件中混合使用,可以在模板文件里面书写任意的PHP语句代码 ,包括下面两种方式: 使用php标签 例如: {php}echo 'Hello ...