Skip to content
This repository has been archived by the owner on Jan 29, 2023. It is now read-only.
/ microstruct Public archive

Less than 1KB (gzipped) subset of Superstruct specialized in validating and typing data decoded from JSON.

License

Notifications You must be signed in to change notification settings

iorate/microstruct

Repository files navigation

Microstruct

Less than 1KB (gzipped) subset of Superstruct specialized in validating types of data decoded from JSON.

Example

// https://github.com/ianstormtaylor/superstruct#usage

import { is, object, number, string, array } from 'microstruct';

const Article = object({
  id: number(),
  title: string(),
  tags: array(string()),
  author: object({
    id: number(),
  }),
});

const data: unknown = {
  id: 34,
  title: 'Hello World',
  tags: ['news', 'features'],
  author: {
    id: 1,
  },
};

if (is(data, Article)) {
  // `data` is guaranteed to be of type `{ id: number; title: string; tags:
  // string[]; author: { id: number } }` in this block.
}

Main Differences to Superstruct

No Error Messages

Error reporting is outside the scope of Microstruct. Friendly error messages are not necessary unless disclosed to end users.

No Support for create and mask

Because Microstruct is specialized in validating types of data decoded from JSON, create and mask are not supported.

parse: A Type-safe JSON Parser

parse(json, struct) returns a typed value parsed from json if it is valid, otherwise undefined.

const json = '{"result":true, "count":42}';

const value = parse(json, object({ result: boolean(), count: number() }));

if (value !== undefined) {
  // `value` is guaranteed to be of type `{ result: boolean; count: number }` in
  // this block.
}

Getting Started

npm install microstruct
# or
yarn add microstruct

To use Microstruct with TypeScript, typescript >=4.1.2 is required.

Author

iorate (Twitter)

License

Microstruct is licensed under MIT License.

About

Less than 1KB (gzipped) subset of Superstruct specialized in validating and typing data decoded from JSON.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published