【发布时间】:2020-10-18 10:50:37
【问题描述】:
我的compose函数其实很简单:
const compose = (outer: any, inner: any) => (...innerParams: any) =>
outer(inner(...innerParams));
当我现在这样做时:
const theInner = (p1: string, p2: string): string => [p1, p2].join(' ');
const theOuter = (p1: string): number => p1.length;
const theComposed = compose(theOuter, theInner);
const theResult = theComposed('asdf', 'asdf');
当我将鼠标悬停在 theComposed 和 theResult 上时,VSCode 的类型提示会显示 const theComposed: (...innerArgs: any) => any 我得到 const theResult: any。
所以所有类型都丢失了。
我一直在尝试几种方法来使用泛型来完成这项工作,但不幸的是,我似乎无法解决这个问题。
这是我的失败之一:
export const compose = <
T extends CallableFunction,
U extends CallableFunction,
PT extends ThisParameterType<U>
>(
outer: T,
inner: U
) => (...args: PT[]) => outer(inner(args));
这导致theComposed 显示const theComposed: (...args: unknown[]) => any 和theResult 仍然是任何。
无论如何,我为返回类型尝试的大多数事情都只会让 typescript 编译器对我发火。
我想要的结果是:
const theComposed: (p1: string, p2: string) => number
这样可行吗?
TIA。
【问题讨论】:
-
你能发布一个 Typescript Playground 吗?
标签: typescript typescript-generics