流程如何推导为递归函数类型?

时间:2018-10-29 09:07:22

标签: javascript functional-programming flowtype

我写了这样的函数:

const andThen = it => then => then === undefined ? it : andThen(it/* == null ? it : */ && then(it));

希望它能像其他语言的空安全糖一样工作,例如kotlin的?.let

o?.let { fn(it.a) }.?let { gn(it.b) }?.let { hn(it.c) }

但是,如果使用此功能,我将无法获得友好的IDE类型提示:

const r = andThen(1)(it => it + 1)(it => it * 2)(); // expected `number`, but got `any`.

所以我想为此添加一个flow定义:

// try to typed `andThen`:
type AndThen<It> = (thenFn?: <Then>(it: It) => Then) => It | AndThen<Then>/* AndThen<Then, any> //how to define that? */;

但是flow似乎无法推断出递归函数的类型是行不通的。

const ok = (() => {
    const fn = (it: 1): AndThen<1> => thenFn => thenFn === undefined ? it : andThen(it && thenFn(it));
    const r = fn(1);
    const rr = r(() => 2); // expected: `1 | AndThen<2>`, got `any`.
    // const rrParam = (_it: 1) => 2; const rr = r(rrParam); // not work too.
    return rr() === 2;
})();

正确的方法是什么?

0 个答案:

没有答案