如何为 cons 单元生成通用的 TypeScript 类型签名?

How to generate a generic TypeScript type signature for a cons cell?

我正在努力寻找 cons 单元格的通用类型签名,它允许键入选择器函数。

即我要输入的代码:

const cons = (head, tail) => selector => selector(head, tail);

我想分配一个泛型类型,其中类型 T 是头部,类型 V 是尾部。

我精心打字的一些尝试是:

const cons: <T,V>(head: T, rest: V) => (selector: (head: T, rest: V) => T | V) => T | V 
    = (head, rest) => selector => selector(head, rest);

上面代码的问题是我找不到适用于选择器函数 head 的类型签名,实现:

const head = list => list((head, rest) => head)

我总是得到错误 “需要 2 个参数,但得到 1 个。”在 list((head, rest) => head) 下。

我只是无法让泛型工作!任何帮助将不胜感激!谢谢!

编辑 - 添加了预期行为示例(无类型)

const cons = (head, tail) => selector => selector(head, tail);
const head = list => list((head, tail) => head);
const rest = list => list((head, tail) => tail);
let someList = cons(1, cons(2, cons(3, null)));
head(someList);
// returns: 1
rest(someList);
// returns: cons(2, cons(3, null))

你的const类型和我的一模一样。为了清楚起见,我只是拆分了许多部分。我添加的唯一新类型是 selectorFuncWrapper,我想这正是您要找的。

原代码保留。检查它是否适合您。

type selector<H, T> = (head: H, tail: T) => (H | T);
type selectorFunc<H, T> = (selector: selector<H, T>) => (H | T);
type consFunc<H, T> = (head: H, tail: T) => selectorFunc<H, T>;
type selectorFuncWrapper<H, T> = (list: selectorFunc<H, T>) => selectorFunc<H, T>;

const cons: consFunc<number, any> = (head, tail) => selector => selector(head, tail);

const head: selectorFuncWrapper<number, any> = list => list((head, tail) => head);
const rest: selectorFuncWrapper<number, any> = list => list((head, tail) => tail);

let someList = cons(1, cons(2, cons(3, null)));

head(someList);
// returns: 1
rest(someList);
// returns: cons(2, cons(3, null))