ununknown
TypeScript icon, indicating that this package has built-in type declarations

0.4.6 • Public • Published

ununknown

npm version

Typesafe combinatorial data validators/parsers for typescript using fp-ts.

Documentation is available here.

Installation

npm install ununknown

Outline

The crux of the problem this library solves is the following: How do we ensure that an object of type unknown is actually of type T in our typescript project? This problem comes up in several situations, including, if not limited to:

  • REST APIs
  • Javascript Interop
  • JSON RPCs

Example

import { array, field, isSuccess, object, Parser, recursive, runParser, runParserEx, thing } from "../src";

interface Person {
  name: {
    first: string;
    last: string;
  };
  age?: number;
  children: Array<Person>;
}

const personValidator: Parser<Person, unknown> = recursive(() =>
  object.of({
    name: field.required(
      "name",
      object.of({
        first: field.required("first", thing.is.string),
        last: field.required("last", thing.is.string)
      })
    ),
    age: field.optional("age", thing.is.number),
    children: field.required("children", array.of(personValidator))
  })
);

// Check if validation succeeded

const test = {
  name: {
    first: "Kaden",
    last: "Thomas"
  },
  age: 20,
  children: []
};

// Throws an error with result.left if it fails
const result: Person = runParserEx(personValidator, test);

// Non-exception based
const parseResult = runParser(personValidator, test);
if (isSuccess(parseResult)) {
  const o: Person = parseResult.right;
  console.log("succeeded");
} else {
  console.log("failed with error: ", parseResult.left);
}

Caveats

  • Circular references are not handled, which should not affect anything encoded in JSON. However, this is a valid validation case and will be handled in the future.

Readme

Keywords

none

Package Sidebar

Install

npm i ununknown

Weekly Downloads

2

Version

0.4.6

License

MIT

Unpacked Size

768 kB

Total Files

46

Last publish

Collaborators

  • tkaden4