Hacker News new | ask | show | jobs
by nkingsy 1291 days ago
TypeScript can type based on object literals, so while you can't type JSON on the fly, you can type a JSON file automatically.

With code gen you can usually just print out your JSON directly from the source and import that as a type into your source code.

This is why apis are moving towards specifications that trigger multiple generators.

JSON typing is possible without generation, but more cumbersome.

interface TypedJSON {

  string?: string;

  number?: number;

  array?: TypedJSON[];

  boolean?: boolean;

  object?: {[key: string]: TypedJSON}
}

{foo: {string: "my string"}, bar: {number: 4}}

Probably makes sense to make the "string" key "s" for minimal payload size impact, or this could also be done by converting standard JSON to this typed representation at runtime.