0.4.6 • Published 4 years ago

ununknown v0.4.6

Weekly downloads
2
License
MIT
Repository
github
Last release
4 years ago

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.
0.4.5

4 years ago

0.4.6

4 years ago

0.4.4

4 years ago

0.4.3

4 years ago

0.4.2

4 years ago

0.4.1

4 years ago

0.4.0

4 years ago

0.3.5

4 years ago

0.3.4

4 years ago

0.3.3

4 years ago

0.3.2

4 years ago

0.3.1

4 years ago

0.3.0

4 years ago

0.2.4

4 years ago

0.2.3

4 years ago

0.2.2

4 years ago

0.2.1

4 years ago

0.2.0

4 years ago

0.1.0

4 years ago