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. PostgreSQL指定用户可访问的数据库pg_hba.conf

    进入指定目录: # cd /var/lib/pgsql/9.3/data/ 使用vi编辑pg_hba.conf文件 # vi pg_hba.conf 以上配置为所有IP及网关都允许访问,使用MD5认证 ...

  2. tab.py

    vim tab.py #!/usr/bin/env python # #Tab import sys import readline import rlcompleter import atexit ...

  3. 以替换为主的疯狂填词、sub()介绍

    去年接到一个任务,一直给拖到了今天,再这么下去可不行,今天我就要让你们看看我的厉害 任务是这样的:创建一个程序,读入文本文件,并让用户在该文本出现ADJECTIVE .NOUN.ADVERB或VERB ...

  4. gcc/g++命令参数笔记

    1. gcc -E source_file.c -E,只执行到预编译.直接输出预编译结果. 2. gcc -S source_file.c -S,只执行到源代码到汇编代码的转换,输出汇编代码. 3. ...

  5. Linux Network配置

    /etc/sysconfig/network [root@mytest ~]# cat /etc/sysconfig/network NETWORKING=yes HOSTNAME=mytest /e ...

  6. GenIcam标准(五)

    2.8.10.Enumeration, EnumEntry Enumeration节点把一个名称(name)映射到一个索引值(index value),并实现Ienumeration接口.Enumer ...

  7. java反射机制剖析(二)— Class Loader

    上一篇博客简要的提了一下java反射机制中涉及到的一些相关知识,那么ClassLoader就是当中之中的一个.本篇博客就具体的对ClassLoader做一个相对深入的了解. 作为了解须要知道的是.事实 ...

  8. IOS-7-纪念一下刚刚接到的第一份offer(下面是面试遇到的问题)

    1.多线程技术 有四种开启线程的方式,基本的为:NSThread.NSOperation.GCD:还有一种已经老掉牙了.基于C语言.就不写了,基本不用. 样例:家在网络图片显示在手机界面上 第一步:代 ...

  9. legend---二、如何降低编程复杂度

    legend---二.如何降低编程复杂度 一.总结 一句话总结:配置文件,数据库 个性的东西可以一起写入数据库,那么编程复杂度会大幅降低,页面灵活度也大幅降低(特有属性写进数据库) 比如不同难度的颜色 ...

  10. lightoj--1008--Fibsieve`s Fantabulous Birthday(水题)

    Fibsieve`s Fantabulous Birthday Time Limit: 500MS   Memory Limit: 32768KB   64bit IO Format: %lld &a ...