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

最新文章

  1. RealSense开发-搭建C#开发环境
  2. Ubuntu中设置静态IP和DNS
  3. WPF listbox UI虚拟化
  4. jQuery $.extend() 和 $.fn.extend() 用法
  5. 一样的Android,不一样的学习
  6. 使用c#将多个文件放入文件夹中,并压缩下载
  7. android WebViewClient的方法解释
  8. Linux 离线安装Rubygems详解
  9. How the Microsoft Bot Framework Changed Where My Friends and I Eat: Part 1
  10. 深入学习 Java 序列化
  11. django 数据库配置 ,APP 迁移.模型基础
  12. MySQL安全模式:sql_safe_updates讲解
  13. read命令
  14. MacOS下MySQL配置
  15. Django的quarySet
  16. mac上php+nginx配置
  17. javascript构造函数及原型对象
  18. 【windows c】 遍历目录
  19. [转载]Java给word中的table赋值
  20. &lt;2013 12 28&gt; AOI PCB设计

热门文章

  1. 旧机器安装ArchLinux的各种问题
  2. 解决HMC在IE浏览器无法登录的问题(Java Applet的使用问题)
  3. 洛谷 P2015 二叉苹果树 && caioj1107 树形动态规划(TreeDP)2:二叉苹果树
  4. 浴谷 P1768 天路
  5. python里面 __future__的作用 &amp; 下划线的作用 &amp; 3.0实现不换行
  6. 《Java并发编程实战》第五章 同步容器类 读书笔记
  7. resin后台输出中文乱码的解决的方法!
  8. BZOJ2895: 球队预算
  9. POJ 3276 枚举+差分?
  10. Sql Server通用分页存储过程