[英]Return type of generic function
我试图让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);
该代码只是一个示例,在生产中getResults
function 用于合并分页请求的结果( fn
在这种情况下是请求函数)
所以,我不确定这是否也涵盖了您生产所需的东西。 但是返回类型看起来像这样:
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);
编辑:我实际上不确定为什么有问题的代码没有提供正确的 IntelliSense,这对我来说很有意义。
但我可以看到,您使用了三种泛型类型T
、 R
和P
。 我的想法是,基本上你只有 2 种类型需要担心,它们是参数和方法的结果。
我基本上是说, getValue
的IResponse
中的任何类型都将是 myResults function 的最终myResults
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.