Conditional types take generics one step further and allow you to test for a specific condition, based on which the final type will be determined. We will look at how they work on a basic level and then leverage their power to allocate function types dynamically based on the type of their parameters, all without any overloads.

For example, the following code, the 'contianer' type is 'any'

interface StringContainer {
value: string;
format(): string;
split(): string[]
} interface NumberContainer {
value: number;
neatestPrime: number;
round(): number;
} type Item<T> = {
id: T,
container: StringContainer | NumberContainer
} let item: Item<string> = {
id: 'ad',
container: null
} item.container.value;
item.container.split(); // Compiler error

Conditional Type can help with this:

type Item<T> = {
id: T,
container: T extends string ? StringContainer : NumberContainer
}

We can build 'ArrayFilter' type to only get Array based type:

type ArrayFilter<T> = T extends any[] ? T : never;
type StringsOrNumbers = ArrayFilter<string | number | string[] | number[]>

It filters out 'string, number' type becasue they are not match 'any[]' Array type. And 'never' type is ignored.

Conditional type can replace function overloads:

interface Book {
id: string;
tableOfContent: string[];
} interface Tv {
id: number;
diagonal: number;
} interface IItemService {
getItem(id: string): Book;
getItem(id: number): Tv;
getItem<T>(id: T): Book | Tv;
} let itemService: IItemService;

We can replace the hightlighted function overloads with contidional types:

interface IItemService {
getItem<T>(id: T): T extends string ? Book: Tv;
}

[TypeScript] Dynamically Allocate Function Types with Conditional Types in TypeScript的更多相关文章

  1. 深入浅出TypeScript(5)- 在React项目中使用TypeScript

    前言 在第二小节中,我们讨论了利用TypeScript创建Web项目的实现,在本下节,我们讨论一下如何结合React创建一个具备TypeScript类型的应用项目. 准备 Webpack配置在第二小节 ...

  2. [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 ...

  3. [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 ...

  4. [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 ...

  5. [TypeScript] Overload a Function with TypeScript’s Overload Signatures

    Some functions may have different return types depending on the types of the arguments with which th ...

  6. [TypeScript] Dynamically initialize class properties using TypeScript decorators

    Decorators are a powerful feature of TypeScript that allow for efficient and readable abstractions w ...

  7. [TypeScript] Define a function type

    type DigitValidator = (char) => boolean; -]{}/.test(char); export const digitValidators: {[key: s ...

  8. Java中的Union Types和Intersection Types

    前言 Union Type和Intersection Type都是将多个类型结合起来的一个等价的"类型",它们并非是实际存在的类型. Union Type Union type(联 ...

  9. Unable to create a constant value of type 'System.Object'. Only primitive types or enumeration types are supported in this context.

    代码如下: var query = from s in db.LoginUserServices join ss in db.Services on s.ServiceType equals ss.C ...

随机推荐

  1. iOS 动画整理

    序列帧动画 曾经项目里的一段源码: 1234567891011121314 UIImageView * activityImageView = [[UIImageView alloc] init];N ...

  2. python面向对象之__new__方法

    众所周知,python中定义的类在创建实例对象的时候,会自动执行__init__()方法,但是在执行__init__()方法之前,会执行__new__()方法. __new__()的作用主要有两个. ...

  3. 【 Zabbix 】— 监控nginx

    一.环境说明 OS:centos6.7 x64 nginx:nginx/1.9.9 ZABBIX:2.4.8 zabbix监控nginx是根据nginx的stub_status模块,抓取status模 ...

  4. docker从零开始(四)集群初体验,docker-machine swarm

    介绍 在第三节中,选择了第二节中编写的应用程序,并通过将其转换为服务来定义它应如何在生产中运行,并生成五个应用实例 在本节中,将此应用程序部署到群集上,在多台计算机上运行它.多容器,多机应用程序通过连 ...

  5. hdu 1364(差分约束)

    King Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 12056   Accepted: 4397 Description ...

  6. MATLAB中的符号运算

    1.      syms命令 可以替换sym和symfun,另外可以定义符号变量的类型,如 syms x positive; 限定x为正数. 若要取消这个限定,则可以用命令 syms x clear; ...

  7. 虚拟机vmware下安装Ghost XP——正确的解决方案

    http://hi.baidu.com/xjl456852/item/fd466e9935b2da8859146111 在虚拟机中启动系统,出现"Operating System not f ...

  8. 灯泡游戏 (Kruskal)(并查集)

    灯泡游戏 时间限制: 1 Sec  内存限制: 64 MB提交: 9  解决: 4[提交][状态][讨论版] 题目描述 有 一个n行m列的矩阵,左上角坐标是(0,0),右下角坐标是(n-1,m-1). ...

  9. 自定义编写jmeter的Java测试代码

    我们在做性能测试时,有时需要自己编写测试脚本,很多测试工具都支持自定义编写测试脚本,比如LoadRunner就有很多自定义脚本的协议,比如"C Vuser","JavaV ...

  10. wildfly8.1部署注意事项

    wildfly8.1部署注意事项 jboss  最近新项目上线,本人部署过程中总结了以下几点比较关键的地方,看是否对大家有用处     服务器改成支持外网访问 在standalone.xml文件中找到 ...