来自 immutable.js 的 Iterable 的 flowtype 定义打破了其他库的 Iterables

flowtype definition of Iterable from immutable.js breaks other libs' Iterables

我刚刚将 immutable.js 添加为我的项目的依赖项。我添加了

node_modules/immutable/dist/immutable.js.flow

给我的 .flowconfig.

问题是 immutable 导出一个 Iterable 类型,它也是 node_modules/ 中许多其他库中使用的全局类型,例如 fbjs 和 [=17] =].例如下面的错误之一。

node_modules/fbjs/lib/countDistinct.js.flow:22
22: function countDistinct<T1, T2>(iter: Iterable<T1>, selector: (item: T1) => T2): number {
                                      ^^^^^^^^^^^^ type application of identifier `Iterable`. Too few type arguments. Expected at least 2
32: declare class Iterable<K, V> extends _ImmutableIterable<K, V, typeof KeyedIterable, typeof IndexedIterable, typeof SetIterable> {}
                        ^^^^ See type parameters of definition here. See lib: flow/immutable.js:32

为了解决这个问题,我将 immutable.js.flow 复制到我的项目中并删除了包含它的 .flowconfig 行。在我复制的文件中,我将 Iterable 重命名为 WhateverIterable 并且错误消失了。

无需手动编辑不可变定义即可解决此问题的最佳方法是什么?

主要问题是 node_modules/immutable/dist/immutable.js.flow 没有写成库定义,因此将其用作一个库定义可能会导致错误。

什么是immutable.js.flow

docs 将这些文件称为声明文件immutable.js.flow 位于名为 immutable.js 的文件旁边。每当要求 Flow 要求 immutable.js 时,它都会解析为 immutable.js.flow。您可以使用 flow find-module 命令对此进行测试,该命令显示当 foo.js 导入 immutable:

时 Flow 解析到哪个文件
$ flow find-module immutable foo.js
/Users/glevi/test/immutable/node_modules/immutable/dist/immutable.js.flow

声明文件的编写方式与 libdefs 略有不同。库定义声明了一堆全局的东西。它们声明了哪些变量、函数、类型、类、模块等是全局可用的,并声明了这些东西的类型。声明文件仅声明它们正在隐藏的模块的类型。

immutablejs 的 libdef 看起来像

declare module 'immutable' {
  declare class Iterable<K,V> { ... }
  ...
}

immutable.js.flow 可能看起来像

declare export class Iterable<K,V> { ... }

你应该怎么做

理论上,您不需要将 node_modules/immutable/dist/immutable.js.flow 添加到您的 .flowconfig。每当您的代码导入 immutable.

时,Flow 应该会自动使用它

如果 immutable 附带的 immutable.js.flow 有问题,那么最好的办法是针对 immutable.js.flow or to submit a libdef to flow-typed.

打开拉取请求或问题

快速搜索显示某人 working on a immutable libdef,所以这也可能有帮助!