[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(联 ...
随机推荐
- CodeForcesEducationalRound40-D Fight Against Traffic 最短路
题目链接:http://codeforces.com/contest/954/problem/D 题意 给出n个顶点,m条边,一个起点编号s,一个终点编号t 现准备在这n个顶点中多加一条边,使得st之 ...
- LVS+keepalived均衡nginx配置
如果单台LVS发生突发情况,例如宕机.发生不可恢复现象,会导致用户无法访问后端所有的应用程序.避免这种问题可以使用HA故障切换,也就是有一台备用的LVS,主LVS 宕机,LVS VIP自动切换到从,可 ...
- Unity 模拟点击Home键和启动其他app
using System.Collections; using System.Collections.Generic; using UnityEngine; public class NewBehav ...
- 题解 P3243 【[HNOI2015]菜肴制作】
这道题看起来就是个裸的拓扑排序,抄上模板就能AC. 上面这种想法一看就不现实,然鹅我第一次还真就这么写了,然后被随意hack. 我们需要注意一句话: 现在,酒店希望能求出一个最优的菜肴的制作顺序,使得 ...
- Android编译环境配置
Android编译环境配置 网上关于Android编译环境配置的整理资料有不少,经整理亲测后,希望能给需要的亲们提供帮助. 主要分为四步: 1.安装JDK(Java Standard Edition ...
- Mysql忘记rootpassword
1,停止MYSQL服务,CMD打开DOS窗体.输入 net stop mysql 2,在CMD命令行窗体,进入MYSQL安装文件夹 比方E:\Program Files\MySQL\MySQL Ser ...
- IIS Modules Overview
Introduction The IIS 7 and above Web server feature set is componentized into more than thirty indep ...
- Delegates, Events, and Anonymous Methods 委托、事件与匿名方法
http://www.cnblogs.com/r01cn/archive/2012/11/30/2795977.html
- tp5项目搭建思路
按照需求,创建主体的目录结构,一般包括管理后台admin,前台展示index,app接口api. admin中又包含controller,model,view,其他等等. 一些js,css,image ...
- HDU 4359 Easy Tree DP? 组合数学+动归
题意:定义一种树,每个节点的权值都是20到2n-1,每个权值出现一次,每个节点的左子树的权值和小于右子树,除非只有一个子树.给你n和d,问有n个节点且恰好深度是d的这种树有多少种. 比赛的时候我没有做 ...