Flowtype 函数声明中可重用函数类型的语法

Flowtype 函数声明中可重用函数类型的语法,flowtype,Flowtype,这就是如何将变量/常量注释为包含特定类型的函数: declare type TFunction = () => any; const foo: TFunction = function foo() {}; 声明函数时的语法是什么: function boo() {} ?这个问题讨论得比较晚,但是如果您谈论的声明是“编译时声明,与代码分离,使用declare关键字”,那么根据,您应该能够像这样声明全局变量: declare var boo: TFunction; 或作用域项作为其包含模

这就是如何将变量/常量注释为包含特定类型的函数:

declare type TFunction = () => any;
const foo: TFunction = function foo() {};
声明函数时的语法是什么:

function boo() {}

这个问题讨论得比较晚,但是如果您谈论的声明是“编译时声明,与代码分离,使用
declare
关键字”,那么根据,您应该能够像这样声明全局变量:

declare var boo: TFunction;
或作用域项作为其包含模块或类型的成员:

declare class FunctionHolder {
  boo: TFunction;
}

无法将
:t函数
放在
函数boo()声明中。但是,您可以通过编写no-op语句
(boo:t函数)对其进行流检查之后。唯一的缺点是在运行时计算
boo

不过,最好的方法可能是不必担心显式声明
boo
t函数
,而只要在需要
t函数
的任何时候使用
boo
就可以依靠流来检查它

这里有一个更具体的例子来说明我的意思:()

/*@flow*/
输入算术运算=(a:数字,b:数字)=>数字;
函数添加(a:编号,b:编号):编号{
返回a+b;
}
函数concat(a:string,b:string):string{
返回a+b;
}
函数折叠(数组:数组,运算:算术运算):数字{
返回数组。减少(操作);
}
折叠([1,2,3],添加);//可以,因为add匹配算术运算
褶皱([1,2,3],concat);//流错误,因为concat不匹配
/* @flow */

type ArithmeticOperation = (a: number, b: number) => number;

function add(a: number, b: number): number {
  return a + b;
}

function concat(a: string, b: string): string {
  return a + b;
}

function fold(array: Array<number>, operation: ArithmeticOperation): number {
  return array.reduce(operation);
}

fold([1, 2, 3], add); // ok because add matches ArithmeticOperation
fold([1, 2, 3], concat); // flow error because concat doesn't match