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. 题解 CF383C 【Propagating tree】

    这道题明明没有省选难度啊,为什么就成紫题了QAQ 另:在CF上A了但是洛谷Remote Judge玄学爆零. 思路是DFS序+线段树. 首先这道题直观上可以对于每一次修改用DFS暴力O(n),然后对于 ...

  2. ArcGIS api for javascript——图层-创建WMS图层类型的图层

    本例使用一个WMS端点创建了一个简单的动态图层.首先,代码声明一个新的类my.CityStatesRiversUSAWMSLayer,该类继承esri.layers.DynamicMapService ...

  3. ArcGIS api for javascript——显示多个ArcGIS Online服务

    描述 本例展示了如何使用按钮在地图里的两个不同的图层间切换.所有地图里的图层恰巧是来自ArcGIS Online的ArcGISTiledMapServiceLayers.按钮是Dojo dijit按钮 ...

  4. Linux 下UVC&amp;V4L2技术简单介绍(二)

    通过前文Linux 下UVC&V4L2技术简单介绍(一)我们了解了UVC和V4L2的简单知识. 这里是USB设备的文档描写叙述:http://www.usb.org/developers/do ...

  5. HDU 1730 Northcott Game

    简单的尼姆博弈.想到了非常easy! 就拿一行举例.怎么赢.? 就是死劲挨着对方移,当然假设本身就是挨着的,又轮到你移动了,那么对于这一行来讲.你就是输的!! 由此可见每一行的棋子起始距离就显得尤为重 ...

  6. 理解Linq查询

    using System; using System.Linq; static class Program { static double Square(double n) { Console.Wri ...

  7. export和source的区别

    1.执行脚本是在一个子shell环境运行的,脚本执行完后该子shell自动退出. 2.执行脚本中的系统环境变量(用export定义的变量)才会被复制到子shell中. 3.一个shell中的系统环境变 ...

  8. POJ 3974 Manacher算法(模板)

    Manacher模板题 //By SiriusRen #include <cstdio> #include <cstring> #include <algorithm&g ...

  9. BZOJ 3631 链剖+差分

    思路: 1.树链剖分+用带标记的线段树维护操作(复杂度O(nlog2n)) 2.树链剖分LCA(TarjanLCA等各种LCA)+差分 复杂度(O(n)->O(nlogn)之间) 下面就说说怎么 ...

  10. Vbox下创建Linux和Windows的共享文件夹

    我的Vbox版本是4.3.6...在这里以win8和Ubuntu12.04之间共享文件举例 首先运行虚拟机,然后安装增强功能..这个增强功能很碉堡...能开启无缝模式和系统间的剪贴板共享等牛X功能 然 ...