如何使用附加属性扩展 Flow 函数类型

Hri*_*sto 5 javascript types flowtype

流程 v0.57

我想定义 2 个函数类型,FooFancyFoo帮助类型检查以下模式:

const fooFn = () => ({ id: '...', type: '...' });

fooFn['HELLO'] = 'WORLD';
fooFn['test'] = () => {};

...

// now I can do this:
fooFn();
fooFn.HELLO;
fooFn.test();
Run Code Online (Sandbox Code Playgroud)

第一个函数类型看起来很简单:

type Foo = () => {
  id :string,
  type :string
}
Run Code Online (Sandbox Code Playgroud)

我一直在想第二个。我不清楚如何构建函数类型。

我尝试使用交集:

type FancyFoo = Foo & {
  HELLO :string,
  test :() => mixed
}
Run Code Online (Sandbox Code Playgroud)

然而,这种方法失败了:

// Errors:
2: type FancyFoo = Foo & {
                         ^ property `HELLO` of object type. Property not found in
7: const fooFn :FancyFoo = () => ({ id: '...', type: '...' });
                           ^ function

2: type FancyFoo = Foo & {
                         ^ property `test` of object type. Property not found in
7: const fooFn :FancyFoo = () => ({ id: '...', type: '...' });
                           ^ function
Run Code Online (Sandbox Code Playgroud)

如何定义FancyFoo“扩展”的函数类型Foo但还包含额外属性的函数类型?

链接到 Flow Try


更新

这是我想做的一个更具体的例子:

type Foo = () => { id :string, type :string }

export function getFancyFoo(type :string) :FancyFoo {

  const id :string = randomId();
  const foo :Foo = getFoo(id, type);

  ['A', 'B', 'C'].forEach((thing :string) => {
    foo[thing.toUpperCase()] = thing.toUpperCase();
    foo[thing.toLowerCase()] = () => { /* function that does fancy thing */ };
  });

  return foo;
}
Run Code Online (Sandbox Code Playgroud)

getFancyFoo函数将首先获取一个Foo函数,然后用额外的属性来装饰/增强它。在函数的末尾,foo将如下所示(Chrome 开发工具):

FancyFoo 示例

FancyFoo是一个Foo函数,但它还添加了额外的属性。我一直坚持定义FancyFoo函数类型。

Gaj*_*jus 2

使用可调用对象语法,例如

type OutputInterceptorType = {|
  <T>(routine: () => Promise<T> | T): Promise<T>,
  output: ''
|};
Run Code Online (Sandbox Code Playgroud)