@colinlogue/ts-decode
TypeScript icon, indicating that this package has built-in type declarations

0.2.0 • Public • Published

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

Dependents (0)

Package Sidebar

Install

npm i @colinlogue/ts-decode

Weekly Downloads

0

Version

0.2.0

License

MIT

Unpacked Size

62.1 kB

Total Files

12

Last publish

Collaborators

  • colinlogue