[TypeScript] Infer the Return Type of a Generic Function Type Parameter
When working with conditionals types, within the “extends” expression, we can use the “infer” keyword to either get the type of the elements of an array, or even to get the return type of a function. We can use this to build a “FnReturnType” type, that will give us the return type of the function passed in as the generic parameter.
infer: Typescript can tell the type by itself:
// typescript knows its return type is number
function generateId(seed: number) {
return seed +
} // typescript knows its return type is string
function generateId(seed: number) {
return seed + ""
}
If we have one function, its param type is depend on another function's return type, to make type safety, we have to use Unit type:
function generateId(seed: number) {
return seed + ""
}
function lookupEntity(id: string | number ) {
}
lookupEntity(generateId())
This works, but not good enough, because, unit type can be huge when it grows...
So better typescript can infer the return type and change based on that, to do that we can use conditional type again:
type CustomReturnType<T> = T extends (...args: any[]) => infer U ? U : never;
type Id = CustomReturnType<typeof generateId>; function generateId(seed: number) {
return seed + ""
}
function lookupEntity(id: string | number ) {
}
lookupEntity(generateId())
So 'CustomReturnType should be the infer return type, return type is String then it is String, if number then it is number.
function generateId(seed: number) {
return seed + ""
}
type Id = CustomReturnType<typeof generateId>; // Id is string
function generateId(seed: number) {
return seed +
}
type Id = CustomReturnType<typeof generateId>; // Id is number
Now we can use Id type as param's type:
type Id = CustomReturnType<typeof generateId>;
function lookupEntity(id: Id ) {
}
Actually TypesScript already build it 'ReturnType', works the same the 'CustomReturnType' we just build.
type Id = ReturnType<typeof generateId>;
function lookupEntity(id: Id ) {
}
Knowing this, it is usefully to build a nested infer type:
type UnpackPromise<T> = T extends Promise<infer K>[] ? K : any;
const arr = [Promise.resolve(true)]; type ExpectedBoolean = UnpackPromise<typeof arr>; // Able to know that the value we passed into the promise is boolean
[TypeScript] Infer the Return Type of a Generic Function Type Parameter的更多相关文章
- TypeScript `infer` 关键字
考察如下类型: type PromiseType<T> = (args: any[]) => Promise<T>; 那么对于符合上面类型的一个方法,如何得知其 Prom ...
- Unity3d:Unknown type 'System.Collections.Generic.CollectionDebuggerView'1
问题描述:如图,在调试状态下说:Unknown type 'System.Collections.Generic.CollectionDebuggerView'1<ignore_js_op> ...
- Web api help page error CS0012: Type "System.Collections.Generic.Dictionary'2错误
1.在asp.net Boilerplate项目中,Abp.0.12.0.2,.net framework4.5.2.下载后添加了webApi的helpPage功能,调试出现错误. dubug : a ...
- [TypeScript] Define a function type
type DigitValidator = (char) => boolean; -]{}/.test(char); export const digitValidators: {[key: s ...
- [Typescript] What is a Function Type ? Function Types and Interfaces - Are They Related ?
Function Type: type messageFn = (name: string) => string; function sayHello(name: string): string ...
- 一种封装Retrofit的方法,可以自动解析Gson,回避Method return type must not include a type variable or wildcard: retrofit2.Call<T>的问题
封装目的:屏蔽底层实现,提供统一接口,并支持Gson自动转化 最初封装: //请求方法 interface RequestListener { interface PostListener { @PO ...
- Failed to register: Error: fabric-ca request register failed with errors [[{"code":0,"message":"No identity type provided. Please provide identity type"}]]解决方案
I try to run sample application as stated here : http://hyperledger-fabric.readthedocs.io/en/release ...
- 解决Type safety: The expression of type List needs
解决Type safety: The expression of type List needs unchecked conversion to conform to 在方法前加上这句话就可以了@Su ...
- Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2020-02-06'; nested exception is java.lang.IllegalArgumentException]解决
今天做springbook项目前端输入日期传到数据库保存报了一下错误 Whitelabel Error Page This application has no explicit mapping fo ...
随机推荐
- Java==与equals方法的区别
摘自:http://www.cnblogs.com/dolphin0520/p/3592500.html 1.对于==,如果作用于基本数据类型的变量,则直接比较其存储的 “值”是否相等: 如果作用于引 ...
- javascript中模仿块级作用域
学过 javascript 的都知道 javascript 里面没有块级作用域的概念,这就意味着在块语句中定义的变量,实际上是在包含函数中而非语句中创建的,看下面的例子: function outPu ...
- 用 python 来操作 docx, xlsx 格式文件(一)(使用 xlsxwriter 库操作xlsx格式文件)
需要从数据库读取日志生成相应的 docx,xlsx 文件做相应的记录 所以自然要用到docx, xlsxwriter 库 但是这些库的应用场景非常广泛,任何需要对 word,excel 文件执行重复性 ...
- (五)cobbler自定义系统安装
注意:需要提前获取到物理机对应的网卡的MAC地址,例如我这里使用虚拟机进行演示 cobbler system add --name=linux-node2.com --mac=00:50:56:22: ...
- linux中MySQL本地可以连接,远程连接不上问题
1.网络或防火墙问题 (1)检查网络直接ping你的远程服务器,ping 182.61.22.107,可以ping通说明网络没问题 (2)看端口号3306是不是被防火墙挡住了,telnet 182.6 ...
- window下安装rsyncServer
window下安装rsyncServer---------------------------------1. 解压cwRsyncServer_4.0.5_Installer.zip,安装. 2. 复 ...
- java.net.MalformedURLException: Protocol not found:
出现java.net.MalformedURLException: Protocol not found: 一般来说是url地址没有写对.没有以http://开头,或者出现空格等格式问题: 要看清楚 ...
- 【计算几何】【状压dp】Codeforces Round #226 (Div. 2) D. Bear and Floodlight
读懂题意发现是傻逼状压. 只要会向量旋转,以及直线求交点坐标就行了.(验证了我这俩板子都没毛病) 细节蛮多. #include<cstdio> #include<algorithm& ...
- 【分块】bzoj2724 [Violet 6]蒲公英
分块,离散化,预处理出: ①前i块中x出现的次数(差分): ②第i块到第j块中的众数是谁,出现了多少次. 询问的时候,对于整块的部分直接获得答案:对于零散的部分,暴力统计每个数出现的次数,加上差分的结 ...
- 通过UIImagePickerController选取的图片名称信息
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDic ...