• Stars
    star
    156
  • Rank 239,589 (Top 5 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 7 years ago
  • Updated over 1 year 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,985
star
2

torch

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

scrivener_ecto

Paginate your Ecto queries with Scrivener
Elixir
572
star
4

scrivener

Pagination for the Elixir ecosystem
Elixir
553
star
5

pioneer

Integration Testing
CoffeeScript
527
star
6

stickymojo

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

sass2stylus

Kewl
JavaScript
79
star
8

social-builder

HTML
57
star
9

psd-lint

Clean up your PSDs.
CoffeeScript
38
star
10

pullr

JavaScript
33
star
11

envforcer

Enforce environment variable requirements.
Ruby
30
star
12

capybara-ui

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

EPFImporter

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

backbone.typeahead

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

bricks

Ruby
20
star
16

mo

CSS
10
star
17

helios2

Helios 2.0
Elixir
9
star
18

situation-room

Like pingdom, but with more cachet
JavaScript
9
star
19

foodtrucks_bot

Slack bot for checking Foodtrucks in KP
Elixir
8
star
20

backbone.route-helper

Helper for your backbone routes.
CoffeeScript
8
star
21

PrismatestJS

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

mojo-images

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

feedbag

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

pioneer-todo-mvc

Pioneer tests todo mvc
JavaScript
7
star
25

mojotech-ui

A set of styled React components for MojoTech.com user interfaces.
TypeScript
7
star
26

pivotal-swimlanes

Swimlanes for Pivotal Tracker Sprints
JavaScript
6
star
27

trani.js

Awesome Jquery Interactive Transcript Plugin for Vimeo
JavaScript
5
star
28

backbone.routerFilters

JavaScript
5
star
29

busbus

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

blimey_brackets

Magic Sublime Text bracket closing detector.
Python
4
star
31

entwine

Immutable dependency injection in Node.js
JavaScript
4
star
32

rubo_claus

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

angular-ui-instagram

Angular UI Instagram Directive
CoffeeScript
4
star
34

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
35

pt-estimator

Pivotal Tracker pointing/estimating tool
TypeScript
4
star
36

grunt-pioneer

Grunt runner for pioneer.
CoffeeScript
4
star
37

modernator-haskell

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

semaphorestatus

semaphorestatus
JavaScript
3
star
39

modernator

Moderate.
Clojure
3
star
40

modernator-client-react

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

local

Configure your local dev environment. Boring.
Shell
3
star
42

docker-images

Images of Dockers.
Shell
3
star
43

marionette-ui

UI Toolkit built on Marionette
CSS
3
star
44

pioneer.marionette

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

modash

Useful lodash mixins
CoffeeScript
3
star
46

habit-api

Habit App
Ruby
3
star
47

lunchbot

Elixir
2
star
48

guestbook

Guestbook app
JavaScript
2
star
49

stylus-redesign

The workgroup for Stylus' homepage redesign
2
star
50

heroku-deploy

Ruby
2
star
51

nearest

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

covenant

Ruby
2
star
53

random-run-flutter

Random Run revived with Flutter
Dart
2
star
54

mofun

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

helios2-elixir

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

rails-json-errors

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

rubocop-privacy

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

standauf

HTML
1
star
59

docbert

Literate features.
Ruby
1
star
60

haml-coffee-brunch

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

mocomments

More comments. Please.
CoffeeScript
1
star
62

pivotal-watch

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

node-selenium-webdriver

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

mojo-ghost-s3-adapter

Ghost blog AWS S3 storage adapter
JavaScript
1
star
65

rails_db_protect

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

pioneer-www

JavaScript
1
star
67

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
68

mojotech-design

MojoTech, but make it design
TypeScript
1
star
69

mojotech-intern-docs

MojoTech Internship Documentation
JavaScript
1
star
70

next-props-wiping-bug-demo

Demonstrating a bug with NextJS wiping props
TypeScript
1
star
71

hive

A documentation-driven development revolution
Ruby
1
star