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的更多相关文章

  1. TypeScript `infer` 关键字

    考察如下类型: type PromiseType<T> = (args: any[]) => Promise<T>; 那么对于符合上面类型的一个方法,如何得知其 Prom ...

  2. Unity3d:Unknown type 'System.Collections.Generic.CollectionDebuggerView'1

    问题描述:如图,在调试状态下说:Unknown type 'System.Collections.Generic.CollectionDebuggerView'1<ignore_js_op> ...

  3. 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 ...

  4. [TypeScript] Define a function type

    type DigitValidator = (char) => boolean; -]{}/.test(char); export const digitValidators: {[key: s ...

  5. [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 ...

  6. 一种封装Retrofit的方法,可以自动解析Gson,回避Method return type must not include a type variable or wildcard: retrofit2.Call<T>的问题

    封装目的:屏蔽底层实现,提供统一接口,并支持Gson自动转化 最初封装: //请求方法 interface RequestListener { interface PostListener { @PO ...

  7. 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 ...

  8. 解决Type safety: The expression of type List needs

    解决Type safety: The expression of type List needs unchecked conversion to conform to 在方法前加上这句话就可以了@Su ...

  9. 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 ...

随机推荐

  1. 热安装NGINX并支持多站点SSL

    https://www.moonfly.net/801.html http://www.centoscn.com/image-text/config/2015/0423/5251.html 1.查看n ...

  2. request.getRequestDispatcher(url).forward(request, response)

    request.getRequestDispatcher().forward(request, response) 意思是将客户端的请求转向到 getRequestDispatcher()方法中参数定 ...

  3. apt-get常用命令及工作原理

    https://blog.csdn.net/mosquito_zm/article/details/63684608

  4. (二)centos7安装zabbix agentd端

    关闭防火墙和selinux systemctl stop firewalld systemctl disable firewalld sed -ri '/^SELINUX=/cSELINUX=disa ...

  5. Appium +Python 连接真机测试

    1.数据线连接电脑和手机: 2.用adb获取手机的UUID:cmd-> adb devices 前面的就是你手机的UUID 3.打开appium,选择手机的安卓版本(关于手机中查看),填写手机的 ...

  6. python 执行顺序

    从上往下顺序执行,定义的方法和类要写在调用之前, 如果有 if __name__ == '__main__'   改方法所在的文件作为启动文件时会被调用,如果作为模块被调用时不会被执行.

  7. opencv获取像素的值

    opencv中获取图像像素的方法 方法一: IplImage *img = cvLoadImage("Lena.jpg", 0); CvScalar pixel; for (int ...

  8. (寒假开黑gym)2018 ACM-ICPC, Syrian Collegiate Programming Contest

    layout: post title: (寒假开黑gym)2018 ACM-ICPC, Syrian Collegiate Programming Contest author: "luow ...

  9. Robot Framework与Web界面自动化测试:简单例子

    假设环境已经搭建好了.这里用RIDE( Robot Framework Test Data Editor)工具来编写用例.下面我们对Robot Framework简称rf. 我们先考虑下一个最基本的登 ...

  10. luogu P1215 [USACO1.4]母亲的牛奶 Mother's Milk

    题目描述 农民约翰有三个容量分别是A,B,C升的桶,A,B,C分别是三个从1到20的整数, 最初,A和B桶都是空的,而C桶是装满牛奶的.有时,农民把牛奶从一个桶倒到另一个桶中,直到被灌桶装满或原桶空了 ...