Syntax for reusable function types in function declarations

So you comment on a variable / constant as a function of a certain type:

declare type TFunction = () => any;
const foo: TFunction = function foo() {};

What is the syntax for declaring a function:

function boo() {}

?

+4
source share
2 answers

Unable to place : TFunctionin your ad function boo(). However, you can test it by writing the no-op operator after that (boo: TFunction);. The only drawback is booruntime evaluation .

Probably the best way to do this is not to worry about explicitly stating what it boois TFunction, but instead just relying on Flow to check it anytime you use boowhere TFunctionexpected.

, : ( )

/* @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
+1

, " , , declare", , :

declare var boo: TFunction;

:

declare class FunctionHolder {
  boo: TFunction;
}
0

Source: https://habr.com/ru/post/1664109/


All Articles