[英]Return type of generic function
I'm trying to make getResults
function return the proper type, but currently stuck with this:我试图让
getResults
function 返回正确的类型,但目前坚持这样做:
interface IResponse<T> {
result: T;
}
type FnType<P, R> = (params: P) => R;
const r1: IResponse<string[]> = { result: ['123'] };
const r2: IResponse<number[]> = { result: [456] };
const getResults = <T, R extends IResponse<T[]>, P>(fn: FnType<P, R>, params: P): T[] => {
return [
...fn(params).result,
...fn(params).result
];
};
const getValue = <T>(r: IResponse<T>) => r;
// returned type is unknown[]
// how can we make it return string[]?
getResults(getValue, r1);
// returned type is unknown[]
// how can we make it return number[]?
getResults(getValue, r2);
The code is just an example, in the production getResults
function is used to merge results from a paginated request ( fn
in this case is a request function)该代码只是一个示例,在生产中
getResults
function 用于合并分页请求的结果( fn
在这种情况下是请求函数)
So, I'm not sure this will also cover the things you need for production.所以,我不确定这是否也涵盖了您生产所需的东西。 But the return type looks alright like this:
但是返回类型看起来像这样:
interface IResponse<T> {
result: T;
}
type FnType<P, R> = (params: P) => R;
const r1: IResponse<string[]> = { result: ['123'] };
const r2: IResponse<number[]> = { result: [456] };
const myResults = <P,R>(fn: FnType<P,IResponse<R[]>>, params: P): R[] => {
return [
...fn(params).result,
...fn(params).result
];
}
const getValue = <T>(r: IResponse<T>) => r;
myResults(getValue, r1);
myResults(getValue, r2);
Edit: I'm actually not exactly sure why the code in question does not give correct IntelliSense, it makes sense to me.编辑:我实际上不确定为什么有问题的代码没有提供正确的 IntelliSense,这对我来说很有意义。
But what I can see is that you used three generic types T
, R
and P
.但我可以看到,您使用了三种泛型类型
T
、 R
和P
。 My Idea is that basically you only have 2 types to worry about which are params and the Result of the method.我的想法是,基本上你只有 2 种类型需要担心,它们是参数和方法的结果。
I basically say, whatever type is inside the getValue
's IResponse
will be the final output of the myResults
function.我基本上是说,
getValue
的IResponse
中的任何类型都将是 myResults function 的最终myResults
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.