• Stars
    star
    155
  • Rank 232,407 (Top 5 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 6 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

TypeScript JSON type validation

JSON Type Validation

A TypeScript library to perform type checking and validation on untyped JSON data at runtime.

This library owes thanks to:

Installation

npm i @mojotech/json-type-validation

Projects using < [email protected] will need a polyfill for the unknown type, such as unknown-ts.

Motivation

Let's say we're creating a web app for our pet sitting business, and we've picked TypeScript as one of our core technologies. This is a great choice because the extra stability and type safety that TypeScript provides is really going to help us market our business.

We've defined the data we need to track about each client's pet:

interface Pet {
  name: string;
  species: string;
  age?: number;
  isCute?: boolean;
}

And we've got some data about current client's pets which is stored as JSON:

const croc: Pet = JSON.parse('{"name":"Lyle","species":"Crocodile","isCute":true}')
const moose: Pet = JSON.parse('{"name":"Bullwinkle","age":59}')

But that can't be right -- our data for moose is missing information required for the Pet interface, but TypeScript compiles the code just fine!

Of course this isn't an issue with TypeScript, but with our own type annotations. In TypeScript JSON.parse has a return type of any, which pushes the responsibility of verifying the type of data onto the user. By assuming that all of our data is correctly formed, we've left ourselves open to unexpected errors at runtime.

Unfortunately TypeScript doesn't provide a good built-in way to deal with this issue. Providing run-time type information is one of TypeScript's non-goals, and our web app is too important to risk using a forked version of TypeScript with that added functionality. Type guards work, but are limited in that they circumvent type inference instead of working with it, and can be cumbersome to write.

With json-type-validation we can define decoders that validate untyped json input. Decoders are concise, composable, and typecheck against our defined types and interfaces.

import {Decoder, object, string, optional, number, boolean} from '@mojotech/json-type-validation'

const petDecoder: Decoder<Pet> = object({
  name: string(),
  species: string(),
  age: optional(number()),
  isCute: optional(boolean())
})

Finally, we can choose from a number of decoding methods to validate json and report success or failure. When some json input fails validation the decoder clearly shows how the data was malformed.

const lyle: Pet = petDecoder.runWithException(croc)

const bullwinkle: Pet = petDecoder.runWithException(moose)
// Throws the exception:
// `Input: {"name":"Bullwinkle","age":59}
//  Failed at input: the key 'species' is required but was not present`

Documentation

Documentation.

Building

With Nix

There exists some Nix infrastructure that can be used to reproduce a build environment exactly. A helper shell script lives at bin/jtv that you can use to enter environments for multiple uses. You'll need to follow the directions on the Nix website to install and use the Nix package manager.

  • To enter a shell suitable for building the library run ./bin/jtv build-shell. This will leave you in the root of the project and automatically install any project and npm dependencies. You can run further yarn commands here.
  • To build the library for distribution and exit you can run ./bin/jtv distribute.
  • To enter a build shell and run the build process, watching for changes, run ./bin/jtv build-watch.
  • To run an arbitrary command in a build environment use ./bin/jtv run COMMAND. For example, ./bin/jtv run yarn test will run the tests and exit.

More Repositories

1

jeet

The most advanced, yet intuitive, grid system available for Sass or Stylus
CSS
2,987
star
2

torch

A rapid admin generator for Elixir & Phoenix
Elixir
1,040
star
3

pioneer

Integration Testing
CoffeeScript
528
star
4

stickymojo

A contained fixed positioned sticky sidebar jQuery plugin.
JavaScript
401
star
5

sass2stylus

Kewl
JavaScript
79
star
6

social-builder

HTML
57
star
7

psd-lint

Clean up your PSDs.
CoffeeScript
38
star
8

pullr

JavaScript
33
star
9

envforcer

Enforce environment variable requirements.
Ruby
30
star
10

capybara-ui

Roles and page objects for Capybara integration testing - Formerly called Dill
Ruby
29
star
11

EPFImporter

A Python CLI tool for importing Apple Enterprise Partner Feed data, available to EPF partners, into a relational database.
Python
29
star
12

backbone.typeahead

Integrates typeahead into backbone collections. Inspired by twitter typeahead.
CoffeeScript
21
star
13

bricks

Ruby
20
star
14

mo

CSS
10
star
15

helios2

Helios 2.0
Elixir
9
star
16

situation-room

Like pingdom, but with more cachet
JavaScript
9
star
17

foodtrucks_bot

Slack bot for checking Foodtrucks in KP
Elixir
8
star
18

backbone.route-helper

Helper for your backbone routes.
CoffeeScript
8
star
19

PrismatestJS

Decouple your front-end application tests from the view implementation and make them easier to read and write.
TypeScript
8
star
20

feedbag

TV first, multiuser Github events dashboard for organizations and teams.
CSS
7
star
21

pioneer-todo-mvc

Pioneer tests todo mvc
JavaScript
7
star
22

mojo-images

Packer machine image templates for VMWare, VirtualBox, AWS, and Digital Ocean.
Shell
6
star
23

pivotal-swimlanes

Swimlanes for Pivotal Tracker Sprints
JavaScript
6
star
24

mojotech-ui

A set of styled React components for MojoTech.com user interfaces.
TypeScript
6
star
25

trani.js

Awesome Jquery Interactive Transcript Plugin for Vimeo
JavaScript
5
star
26

backbone.routerFilters

JavaScript
5
star
27

busbus

Like a bus, but more bus.
Objective-C
5
star
28

blimey_brackets

Magic Sublime Text bracket closing detector.
Python
4
star
29

entwine

Immutable dependency injection in Node.js
JavaScript
4
star
30

rubo_claus

Ruby method pattern matching inspired by functional programming
Ruby
4
star
31

angular-ui-instagram

Angular UI Instagram Directive
CoffeeScript
4
star
32

local

Configure your local dev environment. Boring.
Shell
4
star
33

vire

Vire.js is a jQuery plugin that extends the froogaloop library for the Vimeo player. It allows you to execute code at a given point in time in a video.
JavaScript
4
star
34

grunt-pioneer

Grunt runner for pioneer.
CoffeeScript
4
star
35

modernator-haskell

An API server for hosting Reddit AMA style Q&A sessions.
Haskell
4
star
36

modernator

Moderate.
Clojure
3
star
37

modernator-client-react

A small client for mojotech/modernator-haskell
JavaScript
3
star
38

semaphorestatus

semaphorestatus
JavaScript
3
star
39

marionette-ui

UI Toolkit built on Marionette
CSS
3
star
40

docker-images

Images of Dockers.
Shell
3
star
41

pioneer.marionette

Make testing marionette apps with pioneer a pleasant experience
CoffeeScript
3
star
42

pt-estimator

Pivotal Tracker pointing/estimating tool
TypeScript
3
star
43

modash

Useful lodash mixins
CoffeeScript
3
star
44

habit-api

Habit App
Ruby
3
star
45

lunchbot

Elixir
2
star
46

guestbook

Guestbook app
JavaScript
2
star
47

stylus-redesign

The workgroup for Stylus' homepage redesign
2
star
48

heroku-deploy

Ruby
2
star
49

nearest

A node utility for finding the nearest x minutes for a given time
CoffeeScript
2
star
50

random-run-flutter

Random Run revived with Flutter
Dart
2
star
51

covenant

Ruby
2
star
52

mofun

Like regular fun, but mo'.
JavaScript
1
star
53

helios2-elixir

Helios 2 but... in Elixir
JavaScript
1
star
54

rails-json-errors

Easily parse and handle json error packets from a Rails API
CoffeeScript
1
star
55

rubocop-privacy

Vertical alignment code style checking for ruby files
Ruby
1
star
56

standauf

HTML
1
star
57

docbert

Literate features.
Ruby
1
star
58

haml-coffee-brunch

Brunch plugin to compile haml-coffee templates
JavaScript
1
star
59

mocomments

More comments. Please.
CoffeeScript
1
star
60

pivotal-watch

Npm command line tool for watching a pivotal tracker project
JavaScript
1
star
61

hive

A documentation-driven development revolution
Ruby
1
star
62

node-selenium-webdriver

Import of the selenium-webdriver for node.js.
JavaScript
1
star
63

mojo-ghost-s3-adapter

Ghost blog AWS S3 storage adapter
JavaScript
1
star
64

rails_db_protect

Protect your production database from destructive rake tasks
Ruby
1
star
65

pioneer-www

JavaScript
1
star
66

batchelor

Override find_in_batches and find_each in ActiveRecord decendant classes that do not have an integer primary key as these will not work when using PostgreSQL.
1
star