qzb
qzb

Reputation: 8858

Flowtype class declaration incompatible with it's implementation

I have some class (in this example it's named B) defined in b.js file, and it's declaration defined in b.js.flow file. I've assumed that flowtype associates classes with it's declarations, but unfortunately when I've tried to use some function which accepts instance of class B inside it's method flowtype raised following error:

b.js:9
  9:     return this.a.foo(this)
                ^^^^^^^^^^^^^^^^ call of method `foo`
  5: export default class B {
                          ^ B. This type is incompatible with
  6:   foo(b: B): null;
              ^ B. See: a.js.flow:6

I guess it's caused by treating classes as nominal types. Is there any way to associate class implementation with it's declaration to prevent this error?

There is a full content of files which I've used for testing:

a.js:

// @flow

import type B from './b'

export default class A {
  foo(b: B) {
    return null
  }
}

a.js.flow:

// @flow

import type B from './b'

declare export default class A {
  foo(b: B): null;
}

b.js:

// @flow

import A from './a'

export default class B {
  a: A;

  bar() {
    return this.a.foo(this)
  }
}

b.js.flow:

// @flow

import type A from './a'

declare export default class B {
  a: A;
  bar(): null;
}

Upvotes: 1

Views: 406

Answers (1)

Nat Mote
Nat Mote

Reputation: 4086

.js.flow files are not meant to sit side-by-side with their .js counterparts if the .js files are also checked by Flow. The intent was to enable people to publish flow type declarations on npm by (a) transpiling the original source files so people can run them without their own transpile step, and (b) adding the .flow extension to the original source files, which still have types, so Flow can typecheck. flow-typed is preferable to this approach for various reasons, but that's a separate question.

.js.flow files are not meant to be used as .h-style declaration files. Most likely, the best solution to this is to simply remove your .js.flow files. When I tested your example without .js.flow files it typechecked just fine.

Upvotes: 1

Related Questions