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

标签 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();

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

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

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

我尝试使用交集:

type FancyFoo = Foo & {
  HELLO :string,
  test :() => mixed
}

但是,这种方法失败了:

// 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

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

Link to 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;
}

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

FancyFoo example

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

最佳答案

使用Callable Object语法,例如

type OutputInterceptorType = {|
  <T>(routine: () => Promise<T> | T): Promise<T>,
  output: ''
|};

关于javascript - 如何使用附加属性扩展 Flow 函数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47023579/

相关文章:

haskell - Rank2Types/RankNTypes 在没有多型变量的情况下是否实用?

javascript - 联合类型缺少属性

react-native - extends Component 之后的 <{}> 语法是什么?

javascript - 通过右键单击转到链接

c++ - typeid(equalizing) 中类型定义及其含义的区别

javascript - 使用 jQuery 在折叠内的 Bootstrap 4 表中搜索值

c - ptrdiff_t 在 C 中定义在哪里?

javascript - 是否可以关闭所需的流注释?

javascript - 树菜单?在 JS 中?

php - Javascript动态表单提交