【问题标题】:Flow and Ramda dynamic usage?Flow 和 Ramda 动态使用?
【发布时间】:2018-08-05 06:06:06
【问题描述】:

我不确定在哪里报告这个问题或者它是否可以修复,但我认为 Flow 至少应该找到这样一个简单的案例。

const someComponent = (props: Props) =>
   const { children, doesntExist } = props; // Flow error here, great.
   const anotherOne = pick(['doesntExist'], props); // no error here
   // ...

它不应该支持这种情况吗?它是一个错误吗?应该在 ramda 或 flow 的贡献者手中?

【问题讨论】:

  • ramda documentation of pick 表示如果未找到该属性,则将其忽略。也就是说,如果原始对象中不存在键的值,它将是未定义的。由于 API 合约不要求该属性存在,我认为 Flow 不应该引发错误。
  • 问题是,如果 prop 不存在,doesntExistanotherOne 都设置为 undefined,流报告第一个但不报告后者。有意义吗?

标签: flowtype ramda.js


【解决方案1】:

Original Flow type signatures look like this:

declare function pick<A>(
  keys: Array<string>,
): (val: { [key: string]: A }) => { [key: string]: A };
declare function pick<A>(
  keys: Array<string>,
  val: { [key: string]: A }
): { [key: string]: A };

我们可以改成

declare function pick <T>(
  keys: Array<$Keys<T>>,
  val: T
): $Shape<T>;
declare function pick <T>(
  keys: Array<$Keys<T>>
): (T) => $Shape<T>;

结果是

type Props = {
  children: string,
  val: number,
}
const someComponent = (props: Props) => {
  const p1 = pick(['children1'], props); // Flow error here
  const p2 = pick(['children'], props);
  (p2: {children: string});
  // welp, but this is sad
  (p2: {val: number});
}

你可以在Flow playground玩它

如果 TypeScript 是一个选项,请查看 monocle-tsIt provided Flow signatures some times ago, but dropped it,你可以试试把它复活,放到流式repo中。

UPD:也许idx 就是您要找的东西

const p1 = idx(props, (_) => _.children1); // Flow error here

你可以在Flow playground玩它

【讨论】:

    猜你喜欢
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多