Skip to content

Sarcastic Types from JSON — Numio

Generates validators for the sarcastic runtime type-checking library from a JSON sample. Objects become is.shape({...}), arrays is.arrayOf(...), and keys missing from some array items are wrapped in is.maybe(...).

Checking the shape of fetched JSON at runtime in a small JavaScript project without a schema library.

JSON

Sarcastic

When to use it

  • Checking the shape of fetched JSON at runtime in a small JavaScript project without a schema library.
  • Guarding config or message payloads with assertions that throw on unexpected data.

How to use

  1. Paste a JSON object; to mark fields as optional, include array items with and without them.
  2. Read the output: the root shape is RootInterface, nested shapes are named after their keys (posts becomes Posts).
  3. Copy the code and validate data with is(data, RootInterface), which returns the value or throws on a mismatch.

JSON input

{
  "id": 1,
  "name": "Ada",
  "nickname": null,
  "tags": ["math"],
  "posts": [
    { "title": "Notes", "draft": true },
    { "title": "Engine" }
  ]
}

Sarcastic validators

import is from "sarcastic"

const anyValue = (value) => value

const Posts = is.shape({
  title: is.string,
  draft: is.maybe(is.boolean),
})

const RootInterface = is.shape({
  id: is.number,
  name: is.string,
  nickname: is.maybe(anyValue),
  tags: is.arrayOf(is.string),
  posts: is.arrayOf(Posts),
})

Details and limitations

Generated in the browser by the site's own generator, with import is from "sarcastic" added and Prettier formatting applied; no server request.

sarcastic has no "any" assertion, so a value that is only null becomes is.maybe(anyValue), using a small const anyValue = (value) => value helper added to the output.

Integers and decimals are both is.number. Empty arrays become is.array; mixed arrays use is.either, such as is.arrayOf(is.either(is.number, is.string)).

Shapes are declared before the shapes that use them, so the code runs as pasted.

FAQ

How are optional fields represented?

Keys missing from some objects in the same array, or null in some of them, are wrapped in is.maybe(...), which accepts null and undefined. Top-level keys of a single object are always required.

What happens with a root array?

The items are merged into one RootInterface shape describing a single element, and const RootInterfaceList = is.arrayOf(RootInterface) is added for the whole array.

Is sarcastic the same as io-ts or Zod?

No. sarcastic is a smaller library with no static type inference. If you need TypeScript types as well, the JSON to Zod or JSON to io-ts pages are closer.

Specifications and references