Xaree Lee
Xaree Lee

Reputation: 3387

Adding flow types to existing functions

If I got a function from a third-party library, I want to add flow types to it.

For example

 import foo from 'foo';

 // normal call without flowtype check, because foo doesn't use flowtype when declaration
 foo('hello')

 // I want to add param types to function foo
 type FooParamType = 
   | 'only'
   | 'those'
   | 'words'
   | 'are'
   | 'valid'

// I want to re-assign param types to foo
foo(a: FooParamType)

// now I can use foo with flowtype
foo('only')  // good
foo('are')  // good
foo('what') // bad

The function foo has been declared in somewhere else already. How can I add the types to the function?

Upvotes: 0

Views: 101

Answers (1)

Ross Solomon
Ross Solomon

Reputation: 665

Check out the flow-typed project, which has Flow type definitions for hundreds of 3rd party libraries.

If the library you're trying to type does not exist in that project, you can still follow the patterns they use to create your own types.

In your case, one possibility would be to add foo.js to /flow/lib:

declare module 'foo' {
  declare type FooParamType = 
   | 'only'
   | 'those'
   | 'words'
   | 'are'
   | 'valid'

  declare function exports(a: FooParamType): any;
}

You would then just need to add flow/lib under the [libs] section of your .flowconfig.

Upvotes: 2

Related Questions