Type Refinement Function Generation
- Dominant language
- JavaScript
- Stars
- 797
- Forks
- 49
- PR merge metrics
- No merged PRs in 30d
Description
This is a:
- [ ] Bug Report
- [ ] Feature Request
- [x] Question
- [ ] Other
Which concerns:
- [x] flow-runtime
- [x] babel-plugin-flow-runtime
- [ ] flow-runtime-validators
- [ ] flow-runtime-mobx
- [ ] flow-config-parser
- [ ] The documentation website
---
Consider a program that ought to:
1. Take a string as input.
2. Parses this string as JSON.
3. If JSON conforms to a flow type (`User`), continue, otherwise throw an exception and halt.
4. Evaluate some total function over the aforementioned type.
Let's say the type that we'd like to validate against in Step #3 is:
```
type User = {
name: string,
id: number
}
```
For step #2 I can write something like:
```
export type JSON = | string | number | boolean | null | JSONObject | JSONArray
export type JSONObject = { [key:string]: JSON }
export type JSONArray = JSON[]
export const typedJSON = (x: mixed) : JSON => {
switch (typeof x) {
case 'object':
if (x === null) {
return x
} else if (Array.isArray(x)) {
return x.map(typedJSON)
}
const o: JSONObject = {}
for (const k in x) {
o[k] = typedJSON(x[k])
}
return o
case 'string':
case 'number':
case 'boolean':
return x
default:
throw new Error('Invalid JSON')
}
}
```
I could also manually write a function with the signature `(j: JSON) => User` that checks for the presence of the `name`/`id` keys and ensures their values are a string and number respectively, throwing an exception otherwise. How can I generate such validation functions from flow definitions with `flow-runtime` and ensure that flow infers the correct return type?
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.