[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 ...
随机推荐
- python模拟鼠标和键盘操作
import win32api import win32con import win32gui from ctypes import * import time VK_CODE = { 'backsp ...
- slatstack Master的配置
Salt系统非常简单并且易于配置,Salt系统的两个组件都有各自的配置文件.如"salt-master"是通过主配置文件来配置的,"salt-minion"是通 ...
- Vue CLI3 关闭热替换后出现的warning
用vue cli3做项目的时候如果开启了typescript的严格模式,在dev server热替换的时候往往就会打出一大堆warning,严重的影响了编译效率.官方并没有提供关闭warning的ap ...
- 【转】python 生成器和迭代器有这篇就够了
总结得特别好,转自:https://www.cnblogs.com/wj-1314/p/8490822.html 本节主要记录一下列表生成式,生成器和迭代器的知识点 列表生成器 首先举个例子 现在有个 ...
- 【转】requests、BeautifulSoup使用总结
转自,https://www.cnblogs.com/wupeiqi/articles/6283017.html ---- Python标准库中提供了:urllib.urllib2.httplib等 ...
- 二维树状数组+差分【p4514】上帝造题的七分钟
Description "第一分钟,X说,要有矩阵,于是便有了一个里面写满了\(0\)的\(n\times m\)矩阵. 第二分钟,L说,要能修改,于是便有了将左上角为\((a,b)\),右 ...
- UVA Phone List (字典树)(查询是否有前缀或自身是其他的前缀)
Phone List Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 16341 Accepted: 5228 Descr ...
- 循环节(BFS)
循环节 时间限制: 1 Sec 内存限制: 64 MB提交: 56 解决: 16[提交][状态][讨论版] 题目描述 第一节是英语课.今天,老师又教了桐桐很多单词.桐桐发现所有单词都有循环节(大写 ...
- python 连接数据库练习
#!/usr/bin/python# -*- coding:utf-8 -*-import logginglogging.basicConfig(level=logging.INFO)import m ...
- [CTSC2018]混合果汁(二分答案+主席树)
考场上写了60分的二分答案,又写了15分的主席树,然后就弃了.. 合起来就A了啊!主席树忘了开20倍空间最后还炸掉了. 最水的签到题被我扔了,主要还是不会用线段树求前缀和. 做法应该是比较显然的,首先 ...