Artyom Trityak Artyom Trityak - 10 months ago 140
Javascript Question

Flowtype annotation for callback

When i am trying to make this annotation Flowtype does not check types

declare function MyType(x: number): void;
type PropsT = {
onClick?: MyType;

props.onClick && props.onClick(); // no check

but this works.

type PropsT = {
onClick?: (x: number) => void;
props.onClick && props.onClick(); // ERROR

Question - why?

Answer Source

When you write declare function MyType you don't declare a type name MyType, but you declare that a function MyType with specified signature exists. So, MyType is a value, not a type. Usually, when you use value as a type, Flow will print something like this:

Ineligible value used in/as type annotation (did you forget 'typeof'?)

The only exception is functions. Flow allows use functions as type to support old style classes:

function Foo() {}
const foo: Foo = new Foo();

Unfortunately, behaviour of such classes is mostly unsafe, Flow infers type of some properties, but treats everything else as any.

Long story short, you need to add typeof:

type PropsT = {
  onClick?: typeof MyType;