@colinlogue/ts-decode
v0.2.0
Published
Safely decode untyped data to a known type.
Downloads
3
Readme
TypeScript Decoders
Safely decode untyped data to a known type.
Example
// Define a type for the data, and any validators.
// -----------------------------------------------
type UserInfo = {
name: {
first: string,
last?: string
},
username: string
}
function isValidUsername(username: string): boolean {
return !(username.includes(' '));
}
const invalidUsernameMessage = "spaces not allowed";
// Define a Decoder for the data.
// ------------------------------
const userInfo = scheme({
name: scheme<{first: string, last?: string}>({
first: string,
last: optional(string)
}),
username: string.check(isValidUsername)
});
// Use the Decoder on untyped objects to safely convert to typed data.
// -------------------------------------------------------------------
const validData = JSON.parse(`{
"name": {
"first": "Molly"
},
"username": "molly_malone",
"extra_info": "This will be ignored"
}`);
const res1: Result<UserInfo> = userInfo.decode(validData);
console.log(res1.ok ? res1.value : res1.error);
// { name: { first: 'Molly' }, username: 'molly_malone' }
// Data that can't be decoded will produce an Err variant of Result.
// -----------------------------------------------------------------
const invalidData = JSON.parse(`{
"name": {
"first": "Ronald",
"last": "McDonald"
},
"username": "mickey d"
}`);
const res2: Result<UserInfo> = userInfo.decode(invalidData);
console.log(res2.ok ? res2.value : res2.error);
// while decoding field username: "mickey d": spaces not allowed