流 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
函数类型。
最佳答案
使用Callable Object语法,例如
type OutputInterceptorType = {|
<T>(routine: () => Promise<T> | T): Promise<T>,
output: ''
|};
关于javascript - 如何使用附加属性扩展 Flow 函数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47023579/