The type that this decoder will produce when successful
The Standard Schema interface for this decoder.
Decodes a JSON object of type
The JSON object to decode
A Promise that resolves with the decoded value or rejects with an error message
Parses a JSON object of type
The JSON object to decode
The decoded value of type T
Throws an Error whose message describes the failure and whose cause contains the structured DecodingIssue[]
JsonDecoder.string().parse('hello'); // 'hello'
JsonDecoder.string().parse(123); // throws Error('123 is not a valid string')
// The thrown message prefixes each failure with its location, array indices use bracket notation:
const decoder = JsonDecoder.object({ items: JsonDecoder.array(JsonDecoder.number()) });
decoder.parse({ items: ['x'] }); // throws Error('items[0]: "x" is not a valid number')
If the decoder has succeeded, transforms the decoded value into something else
A new decoder that applies the transformation
// Decode a string, then transform it into a Date
const dateDecoder = JsonDecoder.string().map(stringDate => new Date(stringDate));
// Ok scenario
dateDecoder.decode('2018-12-21T18:22:25.490Z'); // Ok<Date>({value: Date(......)})
// Err scenario
dateDecoder.decode(false); // Err({ issues: [{ message: 'false is not a valid string', path: [] }] })
A decoder that can validate and transform JSON data into strongly typed TypeScript values.
Example
Let's replicate the string decoder: