flow icon indicating copy to clipboard operation
flow copied to clipboard

Flow does not recognize static class properties as properties of the class object

Open dsilva opened this issue 10 years ago • 2 comments

Shouldn't the following type-check? It works fine at runtime.

/* @flow */
function test(props: { prop: number }) {
  console.log('prop', props.prop)
}

const obj = { prop: 1 }

function f(arg: number): void { }
f.prop = 2

class C {
  static prop: number;
}
C.prop = 3

test(obj)
test(f)
test(C)
$ npm install [email protected]
$ node_modules/babel/bin/babel-node.js test.js
prop 1
prop 2
prop 3

But flow complains that C doesn't have a property named prop, even though it does if you consider static properties to be properties of the class.

$ flow
test.js:37
 37: test(C)
     ^^^^^^^ function call
 37: test(C)
          ^ class type: C. This type is incompatible with
 31: function test(props: { prop: number }) {
                          ^^^^^^^^^^^^^^^^ object type


Found 1 error

To get flow to accept test(C), I have to change the type of props to be a union of the previous object type and a class object type restricted by an interface:

declare interface I { static prop: number; }
type _ImplementsI<S: I> = Class<S>
type ImplementsI = _ImplementsI<*>

type Props = { prop: number } | ImplementsI

function test(props: Props) {
  console.log('prop', props.prop)
}

That's relying on the fact that interface types in flow are structural per #1179, but it would be more intuitive to let the object type and the interface-implementation-class-object type mean the same thing.

dsilva avatar Jan 01 '16 04:01 dsilva

This issue seems like it may be somewhat related: https://github.com/facebook/flow/issues/1190

Macil avatar Feb 05 '16 22:02 Macil

I think this is supposed to work, but I can confirm that class types can't currently flow into object types. Investigating to see if that was an intentional change...

samwgoldman avatar Feb 05 '16 23:02 samwgoldman