flow-runtime icon indicating copy to clipboard operation
flow-runtime copied to clipboard

How do I get a list of class properties?

Open adamtal3 opened this issue 7 years ago • 1 comments

This is a:

  • [x] Question

Which concerns:

  • [x] flow-runtime
  • [x] The documentation website

What is the current behaviour?

When importing import t from "flow-runtime"; it looks like all the functions under t are for describing new types. The documentation also talks about describing types and I need to get the description in runtime.


Which package versions are you using?

"flow-runtime": "^0.17.0"


What is the expected behaviour?

I'm searching for a way to examine existing classes.

I've added flow-runtime to my existing project which already uses flow. I have type annotations on every class property in my project.

For example:

export default class SampleClass extends SampleBaseClass {
  name: ? string;
  value: number;
  otherValue: SampleClass2;
}

I've added the following to the start of my babel plugins list: ["flow-runtime", {"assert": false, "annotate": true}].

All I want, is to get an array of properties names so I can validate a JSON parsed object against it.

Can I achieve this behavior with this library?

adamtal3 avatar Nov 27 '18 09:11 adamtal3

Late answer because I'm just randomly browsing through issues, but you can easily use shape types for JSON validation. For example:

type Sample = {|
  name: ?string,
  value: number,
  otherValue: Sample2,
|}

type Sample2 = {|
  // ...
|}

const SampleType = (reify: Type<Sample>)

SampleType.assert({
  name: 'foo',
  value: 1,
  otherValue: {}
})

If you're trying to marshal JSON objects into classes, it may be an uphill battle... for better or worse I think using plain JS objects and making functions that operate on them instead of class methods would probably be easier in the long run. Even Babel outputs AST nodes as plain JS objects instead of class instances AFAIK. (EDIT: Okay, it uses a Node prototype, but it doesn't seem to have any methods, or class hierarchy). This is totally different from how things are done in Java for example, and it took me awhile to get used to it.

jedwards1211 avatar Dec 29 '20 06:12 jedwards1211