【问题标题】:How can I import a module's type into another module interface declaration?如何将模块的类型导入另一个模块接口声明?
【发布时间】:2016-06-27 05:49:50
【问题描述】:

我正在尝试创建一个使用另一个模块声明的模块接口声明,但效果不佳。这是一个 MCVE。我知道我可以将类型注释直接放在本地模块上,但我试图描述我对第三方模块的体验。

.flowconfig:

[ignore]

[include]

[libs]
lib

[options]

[version]
^0.27.0

foo.js:

export class Foo {
  foo() {
    return 'foo';
  }
}

bar.js:

import { Foo } from './foo';

export class Bar extends Foo {
  bar() {
    return 'bar';
  }
  makeFoo() {
    return new Foo();
  }
}

lib/foo.js:

declare module './foo' {
  declare class Foo {
    foo(): string;
  }
}

lib/bar.js:

import { Foo } from './foo';
// Same result if:
// import { Foo } from '../foo';

declare module './bar' {
  declare class Bar extends Foo {
    bar(): string;
    makeFoo(): Foo;
  }
}

index.js:

/* @flow */
import { Foo } from './foo';
import { Bar } from './bar';

const bar = new Bar();
const b: number = bar.bar(); // A. wrong const type
const bf: number = bar.foo(); // B. wrong const type
bar.typo(); // C. no such method

const foo = bar.makeFoo();
foo.foo();
foo.bar();  // D. no such method

flow的结果是:

index.js:6
  6: const b: number = bar.bar(); // wrong const type
                       ^^^^^^^^^ call of method `bar`
  6: const b: number = bar.bar(); // wrong const type
                       ^^^^^^^^^ string. This type is incompatible with
  6: const b: number = bar.bar(); // wrong const type
              ^^^^^^ number


Found 1 error

我预计会出现 4 个错误(index.js 中的 A、B、C 和 D),但只得到 A。似乎我无法在 lib/bar.js 中正确导入 Foo,因此 Foo 变得类似于通配符。

有没有办法将模块的类型正确地导入另一个接口声明?我错过了什么吗?任何帮助表示赞赏。

[编辑]

我在flow-typed 中看到一些声明使用React$Componentwhich is declared globally,但没有导入它。但我想在 Component in react module 这样的模块中使用类型。

【问题讨论】:

    标签: flowtype


    【解决方案1】:

    我认为您不应该创建组件的声明文件,因为 Flow 直接使用源代码。当您需要引用类型时,只需 import 类即可。

    在您当前的示例中,您只是错过了文件顶部的/* @flow */bar.jsfoo.js)。

    【讨论】:

    • 你是对的。但我实际上是在尝试为没有官方声明的第三方库创建声明文件,示例是 MCVE。 stackoverflow.com/help/mcve foo.jsbar.js 没有 /* @flow */ 因为它们是第三方库的示例。
    【解决方案2】:

    很遗憾,Flow 不支持扩展/覆盖 flow/lib 类型:

    https://github.com/facebook/flow/issues/396

    我已经开始做的是:

    1. flow-typed install express@4.x.x
    2. express_v4.x.x.js 从 flow-typed/npm/ 移动到 flow-typed/(在 flow-typed/npm/ 外部,因此它不会被未来的 flow-typed 安装覆盖,在 flow-typed/ 内部,因此 flow 将自动将declare blah 语句设为全局)
    3. 就在declare class express$Request... 的下方(所以很容易找到,所以它在declare module... 内部使用的位置上方,我放了:

      declare class express$Request extends express$Request { user: any; isAuthenticated(): boolean; session: { loginForwardUrl: ?string; }; }

    我这样做而不是将我的自定义道具放在原始类上,以便轻松查看哪些道具是自定义的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-23
      • 1970-01-01
      • 2019-08-08
      • 1970-01-01
      • 2021-07-25
      • 2019-03-21
      • 2018-04-23
      相关资源
      最近更新 更多