我想创建一个实用程序类型,它接受泛型函数及其参数的签名。它应该导致签名的返回类型,就好像它是用提供的参数执行的一样。
我试过这个:
type GetReturnType<T extends (...args: any) => any, B> = T extends (...args: any) => infer R ? R : never;但是所有的泛型最终都是unknown或never。
我可能需要传递一些示例函数:
function myFn1<T>(x: T) {
return {
a: x,
}
}
function myFn2<T>(x: T) {
return [x];
}
function myFn3<T>(x: T) {
if (typeof x == "string") {
return "yes" as (T extends string ? "yes" : "no");
} else {
return "no" as (T extends string ? "yes" : "no");
}
}以及我希望如何使用GetReturnType:
type Return1 = GetReturnType<typeof myFn1, [x: number]>; // expected {a: number}
type Return2 = GetReturnType<typeof myFn2, [x: number]>; // expected number[]
type Return3A = GetReturnType<typeof myFn3, [x: number]>; // expected "no"
type Return3B = GetReturnType<typeof myFn3, [x: string]>; // expected "yes"TypeScript已经有了一个用于推断函数的泛型类型的系统。例如,myFn3("some string")将推断第一个泛型参数为字符串,而返回的值则为"yes"。我想在尝试获取返回类型时使用这个系统。当泛型已知时,关于这方面的其他问题会问如何做到这一点,但我想知道在推断泛型时如何做到这一点。
发布于 2022-11-17 19:08:39
const to = <A>(value: A) => ({ value } as const);
type ApplyTo<A> = ReturnType<typeof to<A>>;
const map = <A extends unknown[]>(value: readonly [...A]) => value.map(to) as {
[K in keyof A]: ApplyTo<A[K]>;
};
type t2 = ReturnType<typeof map<["a", "b", "c"]>>;
// type t2 = [{
// readonly value: "a";
// }, {
// readonly value: "b";
// }, {
// readonly value: "c";
// }]我觉得这已经够近的了。如果我们可以将to作为一个参数传递,会更好,但是afaik是不可能的。
https://stackoverflow.com/questions/70636049
复制相似问题