[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 ...
随机推荐
- 【bzoj1042】硬币购物
容斥 #include<bits/stdc++.h> #define N 100005 typedef long long ll; using namespace std; ll ans, ...
- oracle 一行转多行
比如sql: select zyxdm from table where bindid=2265254 查询结果为:1|4|8|9|10 将这个查询结果转成多行,结果如下: ID 1 4 8 9 10 ...
- 忘记root密码怎么办
忘记root密码有两种解决办法.一种是emergency模式,另一种是rescue模式. 1.emergency模式 这个模式又有人称为单用户模式.使用这种模式,前提是要知道grub密码.一般适用于对 ...
- JavaScript的数组详解
#转载请留言联系 创建数组 1.通过new Array()进行创建 var arr1=new Array(); 2.通过中括号进行创建 var arr2=[]; 计算数组的长度 var arr3=[' ...
- 【计算机网络】http中get和post的区别
常见回答: 1. GET使用URL或Cookie传参.而POST将数据放在BODY中. 2. GET的URL会有长度上的限制,则POST的数据则可以非常大. 3. POST比GET安全,因为数据在地址 ...
- centos 查看 arp
yum install tcpdump -y tcpdump arp :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: ...
- PHP无限极分类详谈
当你学习php无限极分类的时候,大家都觉得一个字“难”我也觉得很难,所以,现在都还在看,因为工作要用到,所以,就必须得研究研究. 到网上一搜php无限极分类,很多,但好多都是一个,并且,写的很乱,代码 ...
- python带cookie提交表单自动登录
import urllib import urllib2 import cookielib login_url = "xxxxxxxxxxxxx" cj = cookielib.C ...
- Unity3D实现DoubleClick的一种方法
代码简单粗暴如下: void OnMouseDown() { ) { t2 = DateTime.Now; , , , , )) //时间间隔小于500ms,认为是双击 { // 双击后的操作 } t ...
- 利用navigator对象判断设备类型
function getTerminalType() { //获取navigator对象 var o = navigator.userAgent, t = ""; if (/\bi ...