JSON to Flow type definitions
Flow, the static type checker from Meta, needs type annotations for the data your code handles. This JSON to Flow generator writes exported type aliases from a sample, starting with the // @flow pragma so Flow checks the file. Nested objects become their own types, arrays become typed arrays, and keys missing from some objects become optional properties.
Example
{ "id": 42, "title": "Write docs", "done": false,
"owner": { "name": "Ada", "email": null },
"subtasks": [ { "title": "Outline", "estimate": 2 }, { "title": "Draft" } ] }
// @flow
export type Task = {
id: number;
title: string;
done: boolean;
owner: Owner;
subtasks: Subtask[];
};
export type Owner = {
name: string;
email: null;
};
export type Subtask = {
title: string;
estimate?: number;
};
The runtime converter
Flow types are erased when the code runs, so they cannot stop malformed data coming from an API. With Types only off, the output adds a Convert module with functions such as Convert.toTask(json) and Convert.taskToJson(value). They parse the JSON string and verify the structure against the types, throwing an error on a mismatch. The module uses CommonJS (module.exports), so require it with const Convert = require("./task").
How types are inferred
Numbers become number, booleans boolean, ISO date strings Date, and arrays T[] or Array<A | B> when elements differ, for example Array<number | string>. A key missing from some objects in the sample becomes optional (estimate?: number), and a property that is always null is typed null. Paste several records rather than one to get accurate optional properties, and give the top-level type a meaningful name in the options so nested types read well.
Refining the types
- Exact objects: Flow object types are exact by default in recent versions; if your project uses an older configuration, write
{| ... |}to forbid extra properties. - Read-only data: prefix properties with
+(+title: string) or wrap types in$ReadOnly<...>to prevent mutation. - Nullable values:
email: nullonly reflects the sample; change it to?string(a maybe type) if the field can hold text. - Dates are typed as
Datewhen the converter is used; with plainJSON.parsethey are strings.
Format the result with the Flow Formatter. For TypeScript projects, JSON to TypeScript generates the equivalent interfaces. Generation runs in your browser.