[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(联 ...
随机推荐
- Linux 基础入门二
1.远程连接 ssh协议:secure shell ~]# ss -tnl 查看系统是否监听在tcp协议的22号接口: ~]# ip addr list 或者 ifconfig 查看ip地址 确 ...
- Object-C,文件路径API
犀利吐槽 1.同样都是"文件和目录操作",java中,就用java.util.File一个类,就封装了很多API,而Object-C搞了这么多类和函数.具体原因,有待分析啊. 2. ...
- UnrealEngine4编码风格的思考
第一次拿到UE4源码,扫了一遍.各种宏定义,各种模板,各种类层次.杂乱无章. 后来慢慢明确其规律: UE4的编码风格是在匈牙利命名法的基础下做了改进,使其更适用游戏引擎业务(业务特点:数据可视编辑.脚 ...
- View 和 ViewGroup 的 hasFocusable
在 android 中.焦点的获取和事件几乎相同,有一个分发机制.一般来说View 树上上层节点的 ViewGroup 比底层节点的 View 有更高的优先级获取焦点.这体如今 ViewGroup 有 ...
- hdu4691 Front compression(后缀数组)
Front compression Time Limit: 5000/5000 MS (Java/Others) Memory Limit: 102400/102400 K (Java/Others) ...
- 找出一堆数中最小的前K个数
描写叙述: 给定一个整数数组.让你从该数组中找出最小的K个数 思路: 最简洁粗暴的方法就是将该数组进行排序,然后取最前面的K个数就可以. 可是,本题要求的仅仅是求出最小的k个数就可以,用排序能够但显然 ...
- 【python下使用OpenCV实现计算机视觉读书笔记2】图像与字节的变换
import cv2 import numpy import os # Make an array of 120,000 random bytes. randomByteArray = bytearr ...
- Armbian hostname and WiFi configuration
In previous post i have described installation of Armbian on Orange Pi PC Plus. Now is the time for ...
- C/C++(C++封装)
封装 当单一变量无法完成描述需求的时候,结构体类型解决了这一问题.可以将多个类型打包成一体,形成新的类型.这是 c 语言中封装的概念.但是,新类型并不包含,对数据类的操作.所的有操作都是通过函数的方式 ...
- BZOJ一句话
一句话题解集合. 1061: [Noi2008]志愿者招募 单纯形,运用对偶原理转化过来,变成标准形然后单纯性裸上即可. #include<cmath> #include<cstdi ...