[TypeScript] Dynamically Allocate Function Types with Conditional Types in TypeScript
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的更多相关文章
- 深入浅出TypeScript(5)- 在React项目中使用TypeScript
前言 在第二小节中,我们讨论了利用TypeScript创建Web项目的实现,在本下节,我们讨论一下如何结合React创建一个具备TypeScript类型的应用项目. 准备 Webpack配置在第二小节 ...
- [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] 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] 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 ...
- [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 ...
- [TypeScript] Dynamically initialize class properties using TypeScript decorators
Decorators are a powerful feature of TypeScript that allow for efficient and readable abstractions w ...
- [TypeScript] Define a function type
type DigitValidator = (char) => boolean; -]{}/.test(char); export const digitValidators: {[key: s ...
- Java中的Union Types和Intersection Types
前言 Union Type和Intersection Type都是将多个类型结合起来的一个等价的"类型",它们并非是实际存在的类型. Union Type Union type(联 ...
- 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 ...
随机推荐
- golang中的反射
反射操作普通变量 package main import ( "fmt" "reflect" ) func main(){ a := 1 //reflect.T ...
- require.js使用baseUrl + paths导入文件配置的3种方法
//main.js requirejs.config({ baseUrl: 'lib/js',//参照于引入这个js文件的index.html页面的相对路径,因为此时mian.js文件已经导入到了in ...
- 【SQL】持久性存储模块PSM
1. 创建PSM函数和过程 创建过程: CREATE PROCEDURE 名字 (参数) 局部声明: 过程体: 创建函数: CREATE FUNCTION 名字 (参数) RETURNS 类型 局部声 ...
- MVC架构中的controller的几种写法
开始写代码之前,我们先来看一下spring MVC概念.一张图能够清晰得说明. 除了controller,我们需要编写大量代码外,其余的都可以通过配置文件直接配置. MVC的本质即是将业务数据的抽取和 ...
- RTP 学习
1. RTP提供抖动补偿和数据无序到达检测的机制 2. RTP 本身并没有提供按时发送机制或其它服务质量(QoS)保证,它依赖于底层服务去实现这一过程. RTP标准定义了两个子协议,RTP和RTCP. ...
- jquerycheckbox事件
https://stackoverflow.com/questions/7031226/jquery-checkbox-change-and-click-event $(document).ready ...
- 理解和上手Redux
顾名思义本文分两个部分,理解和上手,第一部分我先讲个故事,这个故事也许不是特别形象,但对大家理解Redux一定有所帮助.第二部分我举个例子. 先讲个故事: 一个餐厅(应用),我是顾客(用户),这个餐厅 ...
- 走进Spark--云计算大数据新一代技术
什么是Spark? 当然这里说的Spark指的是Apache Spark, Apache Spark™ is a fast and general engine for large-scale dat ...
- (寒假GYM开黑)2018-2019 ACM-ICPC Brazil Subregional Programming Contest
layout: post title: 2018-2019 ACM-ICPC Brazil Subregional Programming Contest author: "luowenta ...
- hdu6138(后缀数组)
hdu6138 题意 给出若干个字符串,每次查询两个字符串,求两个字符串的公共子串且在给出的某一个字符串中作为前缀的最大长度. 分析 求公共子串:后缀数组 判断前缀:字典树 求完后缀数组,遍历下 \( ...