Gajus
Gajus

Reputation: 73818

How to declare an export type for a set of matching files?

I have a folder ./plugins. A plugin has the following interface:

type PluginType = () => Promise<(ad: AdType) => TargetingParameterType>;

In order to use Flow, I need to import PluginType into each plugin script and declare the export type, e.g. this is what I am doing at the moment:

import type {
  PluginType
} from './types';

const myPlugin: PluginType = async () => {
  return (ad) => {
    return {};
  };
};

export default myPlugin;

The problem with this approach is:

  1. It requires to create an intermediate variable (I couldn't find an inline way to annotate export default type)
  2. It requires that this annotation is included in every ./plugins/*.js file.

Is there a way to configure Flow to apply PluginType type to all files in ./plugins/*.js folder without needing to add the type declaration to each file?

Upvotes: 2

Views: 568

Answers (1)

Aurora0001
Aurora0001

Reputation: 13547

You can create project-wide type declarations using ".flowconfig-style" declarations. In your .flowconfig, add:

[libs]

decls/

Then create the directory decls, and in that create a file called plugins.js containing:

declare type PluginType = () => Promise<(ad: AdType) => TargetingParameterType>;    

You may need to include the types that PluginType depends on in this file too.

According to the documentation:

It is similarly useful to declare types. Like other declarations, type declarations can also be made visible to all modules in a project.

To avoid creating an intermediate variable, you can use the typecast syntax:

export default (async () => {
    return (ad) => {
        return {};
    };
}: PluginType);

Upvotes: 3

Related Questions