[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 ...
随机推荐
- 获取mac地址和IP地址方式
第一种 public class OperateMAC{ public static string GetMacByWMI() { string MacAddr = null; //Managemen ...
- Django的缓存机制和信号量相关
缓存介绍 缓存的简介 在动态网站中,用户所有的请求,服务器都会去数据库中进行相应的增,删,查,改,渲染模板,执行业务逻辑,最后生成用户看到的页面. 当一个网站的用户访问量很大的时候,每一次的的后台操作 ...
- eclipse怎么关闭spring dashboard
进入help-install new software-what is already installed?-卸载spring board
- linux下redis的最佳实践(Master-Slave)
本文演示了redis在同一台linux上的安装及运行多个实例,并演示了主从复制,以及如何进行主从的切换. 1. 下载 $ wget http://download.redis.io/releases/ ...
- F - 等式(1/x + 1/y = 1/n)
链接:https://www.nowcoder.com/acm/contest/90/F来源:牛客网 题目描述 给定n,求1/x + 1/y = 1/n (x<=y)的解数.(x.y.n均为正整 ...
- Jquery EasyUI选项卡-Tabs的使用方法
以下是easyUI的tabs的简单实用介绍. var e =$('#main').tabs('exists','accordion'); if(e==true){ $('#main').tabs(' ...
- Codeforces 361D Levko and Array(二分)(DP)
Levko and Array time limit per test 2 seconds memory limit per test 256 megabytes input standard inp ...
- 线程同步CriticalSection
孙鑫 第十五/十六课之四 线程同步CriticalSection 说明 在使用多线程时,一般很少有多个线程完全独立的工作.往往是多个线程同时操作一个全局变量来获取程序的运行结果.多个线程同时访问同一个 ...
- 【数学期望】【高斯消元】bzoj3143 [Hnoi2013]游走
和hdu5955很像.也是注意从结点1出发,其概率要在方程左侧+1. 边的期望和点的期望之间转换巧妙 http://blog.csdn.net/thy_asdf/article/details/473 ...
- 【分块答案】【最小割】bzoj1532 [POI2005]Kos-Dicing
引用zky的题解:http://blog.csdn.net/iamzky/article/details/39667859 每条S-T路径代表一次比赛的结果.最小割会尽量让一个人赢得最多. 因为二分总 ...