[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.
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的更多相关文章
- [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 ...
- 投票通过,PHP 8 确认引入 Union Types 2.0
关于是否要在 PHP 8 中引入 Union Types 的投票已于近日结束,投票结果显示有 61 名 PHP 开发组成员投了赞成票,5 名投了反对票. 还留意到鸟哥在投票中投了反对票~) 因此根据投 ...
- [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 ...
- [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 ...
- [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 ...
- [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 ...
- [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 ...
- [TypeScript] Understand lookup types in TypeScript
Lookup types, introduced in TypeScript 2.1, allow us to dynamically create types based on the proper ...
- Java中的Union Types和Intersection Types
前言 Union Type和Intersection Type都是将多个类型结合起来的一个等价的"类型",它们并非是实际存在的类型. Union Type Union type(联 ...
随机推荐
- 洛谷1073 NOIP2009 最优贸易
题目大意 C 国有 n 个大城市和 m 条道路,每条道路连接这 n 个城市中的某两个城市.任意两个城市之间最多只有一条道路直接相连.这 m 条道路中有一部分为单向通行的道路,一部分为双向通行的道路,双 ...
- CSS 相对/绝对(relative/absolute)定位与jQuery的控制显示隐藏
曾经写显示隐藏老是用jq方法控制: dom.show(); dom.hide(); 事实上这样还是有非常多缺陷的. 这是html结构: <div class="holi"&g ...
- JNI学习积累之二 ---- 数据类型映射、域描述符说明
本文原创,转载请注明出处:http://blog.csdn.NET/qinjuning 在Java存在两种数据类型: 基本类型 和 引用类型 ,大家都懂的 . 在JNI的世界里也存在类似的数据类型,与 ...
- Process Monitor —— 程序(文件和注册表)监控
下载地址:Process Monitor v3.33 通过追踪 Process Monitor 的日志,我们可以确认某程序的行为:
- HtmlHelper的扩展分页方法
一.新建一个空MVC项目,命名为MVCAppPager 二.新建一个文件夹PageHelper,在文件夹下新建接口IPageList以及实现类PageList IPageList接口: public ...
- Redis封装值ZSet
/// <summary> /// Sorted Sets是将 Set 中的元素增加了一个权重参数 score,使得集合中的元素能够按 score 进行有序排列 /// 1.带有权重的元素 ...
- 关于vue中的语法糖v-model
开发src-在线系统的过程中,封装了很多组件,如Dialog prompt等,在开源项目的组件中这些组件使用v-model来控制显示,我来总结一下关于自己学习到的v-model知识 1. 使用prop ...
- Python(七) 高级部分:面向对象
一.类的定义 # 面向对象 #有意义的面向对象代码 # 类 = 面向对象 # 类.对象 #实例化 # 类最基本的作用:封装 class Student(): name = '' age = 0 def ...
- MySQL Pool
创建连接池 function SqlPool() { this.flag = true;//是否连接过 this.pool = mysql.createPool({ host : 'localhost ...
- b模式处理文件
1.读 f=open('cheng','rb') date=f.read() print(date.decode()) 2.写 f=open('cheng','ab') f.write('chengz ...