A strongly typed JSON decoder and validator inspired by Elm, namely the Json.Decode package.
npm 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:
const usersJSON = `{
"users": [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
]
}`
We can create a decoder that matches this expected structure:
import { Decoder, at, array, object, number, string } from 'type-safe-json-decoder'
interface User {
id: number
name: string
}
const usersDecoder: Decoder<User[]> = at(['users'], array(
object({
id: field('id', number()),
name: field('name', string()),
})
))
const 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:
const badJSON = `{
"users": [{"id": "0", "name": "Mallory"}]
}`
usersDecoder.decodeJSON(badJSON)
// throws => error at .users[0].id: expected number, got string
Detalied API documentation can be found here