Typescript从传递的函数返回类型推断返回类型 [英] Typescript infer return type from passed functions return type
问题描述
我想定义一个函数(函数A),它将返回与新函数相同的类型传递给函数A的参数。
例如
导出函数试验< T> (arg:Function):T {
return arg;
函数a():string {
return'a';
}
函数b():数字{
return 0;
}
让aVal:string = test(a);
让bVal:number = test(b);
很显然,这将允许我强烈地键入我的响应来解决一些编译时错误。
有没有人有任何想法或知道我是否只是在做梦。
**注意:
干杯
这个怎么样?
= function test< T>(arg: b $ b return arg();
函数a():string {
return'a';
}
函数b():数字{
return 0;
}
让aVal:string = test(a);
让bVal:number = test(b);
我们没有使用函数接口,而是将arg定义为一个函数,不接受任何参数并返回T的类型。然后,实际类型T可以由传入的函数来定义。
I might be trying to achieve the impossible but here goes.
I want to define a function ( function A ) which will return the same type as a new function passed into the parameter of function A.
e.g.
export function test<T> ( arg:Function ):T {
return arg;
}
function a():string {
return 'a';
}
function b():number {
return 0;
}
let aVal:string = test(a);
let bVal:number = test(b);
Obviously this will allow me to strongly type my responses for some compile time errors.
Does anyone have any ideas or know if I'm just dreaming.
** Note: Code slapped together for demo **
Cheers
How about this?
function test<T>(arg: () => T): T {
return arg();
}
function a(): string {
return 'a';
}
function b(): number {
return 0;
}
let aVal: string = test(a);
let bVal: number = test(b);
Instead of using the Function interface we defined arg as a function that takes no arguments and returns something of type T. The actual type T then can be defined by the function that's passed in.
这篇关于Typescript从传递的函数返回类型推断返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!