[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 ...
随机推荐
- 多个springboot项目部署在同一tomcat上,出现jmx错误
多个springboot项目部署在同一tomcat上,出现jmx错误 原因:因为jmx某些东西重复,禁用jmx就可以了 endpoints.jmx.unique-names=true
- 各种编码UNICODE、UTF-8、ANSI、ASCII、GB2312、GBK详解
来自:http://blog.csdn.net/lvxiangan/article/details/8151670 ------------------------------------------ ...
- linux用grep查找包含两个关键字的命令
linux用grep查找包含两个关键字的命令 http://zhidao.baidu.com/link?url=VsFxeJXmU7W7hy1UH7eT6QAbUsVz9Ru2ABPuWYHWm4kB ...
- js排序(转载)
原文地址:http://blog.csdn.net/wzwlln/article/details/6187732#plain sort(sortfunction)为javascript的数组对象(Ar ...
- hdu 1115(多边形重心问题)
Lifting the Stone Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others ...
- c#读取LOG文件并解决读取提示被其他进程占用问题
c# 读写文件时文件正由另一进程使用,因此该进程无法访问该文件,在IO处理上遇到了无法操作的问题. 文件“C:\u_ex.log”正由另一进程使用,因此该进程无法访问该文件. u_ex.log是一个日 ...
- AC日记——Crane poj 2991
POJ - 2991 思路: 向量旋转: 代码: #include <cmath> #include <cstdio> #include <cstring> #in ...
- AC日记——Red and Blue Balls codeforces 399b
399B - Red and Blue Balls 思路: 惊讶的发现,所有的蓝球的消除都是独立的: 对于在栈中深度为i的蓝球消除需要2^i次操作: 代码: #include <cstdio&g ...
- POJ 2488 A Knight's Journey (回溯法 | DFS)
题目链接:http://poj.org/problem?id=2488 题意: 在国际象棋的题盘上有一个骑士,骑士只能走“日”,即站在某一个位置,它可以往周围八个满足条件的格子上跳跃,现在给你一个p ...
- 百度MapAPI之地理编码
地理编码:将具体地址数据转换为对应坐标点经纬度功能 大致思路: 1.从数据库取得具体地理位置 2.将地址作为参数访问API接口,获取返回数据 3.处理response数据并将经度(lng.longit ...