JD.
JD.

Reputation: 2487

How do you define and import a class type in flow?

Is is possible to define a class type in a file, which gets explicitly imported in another?

for example:

types.js

export type MyType {
  id: number,
  name: string,
};

declare class MyOject {
  constructor(): MyObject;
  getStuff(param: number): MyType;
  ...
}

main.js

import type {MyObject, MyType} from './types.js'; // <- flow does now recognize MyObject
....

I want to be able to import it like in main.js but this violates flow since it doesn't recognize MyObject as a valid import.

I've tried a few different solutions to no success:

Is there a way to define a flow class type and import it explicitly from the file it's defined in?

Upvotes: 1

Views: 2335

Answers (1)

James Kraus
James Kraus

Reputation: 3478

You'll want to use declare export class:

Types.js

// @flow
export type MyType = {
  id: number,
  name: string,
}

declare export class MyObject {
  constructor(): void;

  getStuff(param: number): MyType;
}

Main.js

// @flow
import {MyObject} from './types.js'
import type { MyObject as MyObjectType, MyType } from './types.js'

const newObj: MyObjectType = new MyObject()

As a repo: https://github.com/jameskraus/flow-exporting-declared-class

Upvotes: 1

Related Questions