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
User | Most Recent Commit | # Commits |
---|
Other Committers
User | Most Recent Commit | # Commits |
---|
A strongly typed JSON decoder and validator inspired by Elm, namely the Json.Decode package.
install --save type-safe-json-decoder
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
Detalied API documentation can be found here