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. python基础复习-1-2 数据类型-str、list、tuple、dict

    数据类型 数字 引号: 123 数值 '123' 字符串 整数:ini long 范围:(-2**31 - 2**31) num = 123 长整型 long (L) num = 123L 浮点型:f ...

  2. Selenium2+python自动化61-Chrome浏览器(chromedriver)【转载】

    前言 selenium2启动Chrome浏览器是需要安装驱动包的,但是不同的Chrome浏览器版本号,对应的驱动文件版本号又不一样,如果版本号不匹配,是没法启动起来的. 一.Chrome遇到问题 1. ...

  3. poj 3254(状态压缩+动态规划)

    http://poj.org/problem?id=3254 题意:有一个n*m的农场(01矩阵),其中1表示种了草可以放牛,0表示没种草不能放牛,并且如果某个地方放了牛,它的上下左右四个方向都不能放 ...

  4. (九)MySQL用户和权限管理

    (1)用户管理 1)登录和退出mysql 例: mysql -h192.168.111.150 -P3306 -uroot -predhat mysql -e 'select user,host,au ...

  5. 【cocos2d-js官方文档】十一、cc.path

    概述 该单例是为了方便开发者操作文件路径所设计的.定义为cc.path的目的是为了跟nodejs的path保持一致.里面定义的api也基本跟nodejs的path模块一致,但不全有,今后可能还会继续根 ...

  6. easyui中导航菜单accordion与tree的动态添加

    博客分类: Java Web开发   Js代码   $.parser.parse(); $.ajax({ url:my.bp()+'/main/menuaction!createMenu.action ...

  7. 训练指南 UVALive - 3523 (双联通分量 + 二分图染色)

    layout: post title: 训练指南 UVALive - 3523 (双联通分量 + 二分图染色) author: "luowentaoaa" catalog: tru ...

  8. 29、Django实战第29天:修改密码和头像

    修改头像 1.上传头像,我们需要的对它做一个forms验证,编辑users.forms.py ... from .models import UserProfile class UploadImage ...

  9. linux基本优化

    修改主机名 hostnamectl set-hostname <hostname> 修改终端命令行颜色 # vim /etc/profile 末尾添加 PS1='\[\e[31;40m\] ...

  10. Express下使用formidable实现POST表单上传文件并保存

    Express下使用formidable实现POST表单上传文件并保存 在上一篇文章中使用formidable实现了上传文件,但没将它保存下来. 一开始,我也以为是只得到了文件的相关信息,需要用fs. ...