TypeScript 3.7递归类型给出“类型实例化太深,甚至可能是无限的”

时间:2019-10-14 08:29:58

标签: typescript functional-programming

我正在尝试编写可变参数pipe,该函数由任意数量的单参数纯函数组成。 这种类型的输入应该检查一个函数的返回类型是否是另一个函数的参数类型,依此类推。

我希望它可以在TypeScript 3.7中工作,该脚本引入了递归类型,但以某种方式不起作用并给出了错误:

TS2589: type instantiation is excessively deep and possibly infinite

这是我的代码:

type Tail<T extends any[]> = ((...t: T) => void) extends ((x: any, ...u: infer U) => void) ? U : never;

type Pipe<FNS extends unknown[]> = FNS extends [(a: infer A) => infer B, (b: infer B) => infer C] ? C :
                                 FNS extends [(a: infer A) => infer B, (b: infer B) => infer C, Pipe<[...Tail<FNS>[]]>] ? C : never;

FNS类型表示纯函数数组,而Tail类型应确保仅返回该数组的尾部,但编译器仍将其标记为无限循环。

用法示例:

const numToString = (n: number): string => n.toString();
const toUpper = (s: string): string => s.toUpperCase();

// this works, Foo evaluates to string
type Foo = Pipe<[typeof numToString, typeof toUpper]>;

// this doesn't work, Foo is not evaluated
type Foo = Pipe<[typeof numToString, typeof toUpper, typeof toUpper]>;

此部分有错误:

Pipe<[...Tail<FNS>[]]>

为什么这是无限的?我想念什么?

1 个答案:

答案 0 :(得分:1)

可变参数类型将在未来的roadmap中使用,而不是3.7的一部分。

这是一个备受期待的功能,它将真正启用

中的功能编程

打字稿https://github.com/Microsoft/TypeScript/issues/5453