【发布时间】:2018-04-11 22:11:01
【问题描述】:
流 v0.57
我想定义 2 个函数类型,Foo 和 FancyFoo 来帮助类型检查以下模式:
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 函数类型?
更新
这是我正在尝试做的更具体的示例:
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 是一个Foo 函数,但它还添加了额外的属性。我坚持定义FancyFoo 函数类型。
【问题讨论】:
-
我知道您可以执行以下操作:
type FooExt = { (): Object, HELLO :string, test :() => mixed}。这定义了一个具有两个附加属性的可调用对象(即函数)。但这仅适用于新定义,我认为不适用于现有定义。 -
哦,我不知道
(): Object符号。这是在文档中的什么位置? -
为什么要首先将数据与函数关联?如果你需要某种状态,Javascript 有闭包或生成器函数。
标签: javascript types flowtype