0.0.14 • Published 3 months ago

ts-decode v0.0.14

Weekly downloads
-
License
MIT
Repository
github
Last release
3 months ago

npm version build status codecov

minzipped size Dependency count tree shaking

ts-decode

Straightforward, type-safe unknown => T decoding combinators

Install

# using npm
npm i ts-decode

# using yarn
yarn add ts-decode

Usage

// We can compose the decoders to create new decoders

const personTypeDecoder = oneOf(
  hardcoded("developer"),
  hardcoded("project manager"),
  hardcoded("designer"),
);

const personDecoder = object({
  name: string.required,
  id: number.required,
  kind: personTypeDecoder.required,
  phoneNumbers: array(string).optional,
});

/*
Automagically inferred as:

type Person = {
    name: string;
    id: number;
    kind: "developer" | "project manager" | "designer";
    phoneNumbers?: string[] | undefined;
}
*/
type Person = Infer<typeof personDecoder>;

// The decoder can now validate a value of unknown type
const json = JSON.parse(`
  { "name": "John Doe",
    "id": 1234,
    "kind": "project-manager",
    "phoneNumbers": ["123123123"]
  }
`);

const result = personDecoder.decode(json);

if (result.error === false) {
  // now we have the compile-time guarantee that this
  const person = result.value;
  // has type `Person` without manual casting
} else {
  // Or if it failed we can log the error description
  const reason = result.reason;
  console.error(reasonToXmlString(reason));
}

By the way, did you notice the bug? Good thing we printed it out

<field-type name="kind">
  <one-of>
    <fail> Expected "developer", got "project-manager" instead  </fail>
    <fail> Expected "project manager", got "project-manager" instead  </fail>
    <fail> Expected "designer", got "project-manager" instead  </fail>
  </one-of>
</field-type>

You can find the complete typedocs-generated API here or you can try it in a codesanbox

0.0.13

3 months ago

0.0.14

3 months ago

0.0.12

2 years ago

0.0.11

2 years ago

0.0.10

2 years ago

0.0.9

2 years ago

0.0.8

2 years ago

0.0.7

2 years ago

0.0.6

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago