TypeScript type annotations provide compile-time guarantees. However, when data flows into our clients from external sources, many things can go wrong at runtime.

JSON decoders validate our JSON before it enters our program. This way, if the data has an unexpected structure, we're immediately alerted.

type User = {
firstname: string;
lastname: string;
};

const userDecoder = JsonDecoder.object<User>(
{
firstname: JsonDecoder.string,
lastname: JsonDecoder.string
},
'User'
);

const jsonObjectOk = {
firstname: 'Damien',
lastname: 'Jurado'
};

userDecoder
.decodeToPromise(jsonObjectOk)
.then(user => {
console.log(`User ${user.firstname} ${user.lastname} decoded successfully`);
})
.catch(error => {
console.log(error);
});

Data Structures

array
dictionary
emptyObject
enumeration
lazy
object
objectStrict
tuple

Primitives

boolean
number
string

Transformations

failover
isNull
isUndefined

Types

Decoder
DecoderObject
DecoderObjectKeyMap

Utils

constant
fail
isExactly
nullable
oneOf
optional
succeed