polleverywhere/type-safe-json-decoder

Name: type-safe-json-decoder

Owner: Poll Everywhere

Description: A strongly typed JSON decoder and validator inspired by Elm

Created: 2018-03-22 13:31:26.0

Updated: 2018-03-22 16:15:38.0

Pushed: 2018-03-22 16:15:48.0

Homepage: https://ooesili.github.io/type-safe-json-decoder

Size: 161

Language: TypeScript

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

Type-safe JSON Decoder

wercker status typedoc npm npm

A strongly typed JSON decoder and validator inspired by Elm, namely the Json.Decode package.

Installation
install --save type-safe-json-decoder
Introduction

Parsing JSON introduces an unfortunate any in to TypeScript programs. The objects returned from JSON.parse often become the data sources for entire applications, never once validated against the actual interfaces and classes which they go into. This module allows for the creation of decoders which perform runtime type checks on the input and return a fully typed result.

Given this JSON input:

t usersJSON = `{
sers": [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}


We can create a decoder that matches this expected structure:

rt { Decoder, at, array, object, number, string } from 'type-safe-json-decoder'

rface User {
: number
me: string


t usersDecoder: Decoder<User[]> = at(['users'], array(
ject(
['id', number()],
['name', string()],
(id, name) => ({id, name})



t users: User[] = usersDecoder.decodeJSON(usersJSON)

The important thing to note here is that decodeJSON does not return any. It returns a type assignable to User[].

A decoder will also a throw nice error message if it comes across an unexpected value at runtime:

t badJSON = `{
sers": [{"id": "0", "name": "Mallory"}]


sDecoder.decodeJSON(badJSON)
hrows => error at .users[0].id: expected number, got string
Documentation

Detalied API documentation can be found here


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.