[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
最新文章
- Lookup component 用法
- EntityFramework 分页问题探讨之 OrderBy
- IOS开发之开发者账号遇到的bug
- [MetaHook] Surface hook
- iOS9适配 之 关于info.plist 第三方登录 添加URL Schemes白名单
- 1.No MBR错误
- JS模块化工具requirejs教程(二):基本知识
- C# Socket编程笔记(转)
- (转)c语言_链表实例讲解(两个经典例子)
- C/C++:作用域、可见性与生存期
- ES各种错误解决
- QT5删除隐藏目录+隐藏文件
- 浙江大学2015年校赛B题 ZOJ 3861 Valid Pattern Lock
- 优化viewHolder
- SQL反模式学习笔记21 SQL注入
- css实现礼券效果
- sql server 查询某个表被哪些存储过程调用
- VM 操作系统实例化(基于 KVM 的虚拟化研究及应用--崔泽永(2011))的论文笔记
- Animator根运动清除刚体速率问题测试
- 学习笔记之C# 教程 | 菜鸟教程