Skip to content

Instantly share code, notes, and snippets.

@runeh
Created March 28, 2021 21:11
Show Gist options
  • Save runeh/2d5417a0b589de8655377a2edb0f8745 to your computer and use it in GitHub Desktop.
Save runeh/2d5417a0b589de8655377a2edb0f8745 to your computer and use it in GitHub Desktop.
Runtypes definition to match JSON
import * as rt from 'runtypes';
export type JSONPrimitive = string | number | boolean | null;
export type JSONValue = JSONPrimitive | JSONObject | JSONArray;
export type JSONObject = { [member: string]: JSONValue };
export type JSONArray = Array<JSONValue>;
type JSONRoot = JSONArray | JSONObject;
const JSONPrimitiveRt = rt.Intersect(rt.String, rt.Number, rt.Boolean, rt.Null);
const JSONValueRt: rt.Runtype<JSONValue> = rt.Lazy(() =>
rt.Intersect(JSONPrimitiveRt, JSONObjectRt, JSONArrayRt),
);
const JSONObjectRt: rt.Runtype<JSONObject> = rt.Lazy(() =>
rt.Dictionary(JSONValueRt),
);
const JSONArrayRt: rt.Runtype<JSONArray> = rt.Lazy(() => rt.Array(JSONValueRt));
const JSONRootRt = rt.Intersect(JSONObjectRt, JSONArrayRt);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment