0.0.16 • Published 3 years ago

zfn v0.0.16

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

zfn

A tiny function for writing TS functions with runtime validation.

Build

Install

npm install zfn

Example

Works with myzod and zod.

import { Zfn } from "zfn";
import * as z from "myzod";
// Alternatively you could use zod
// import * as z from "zod";

const greet = Zfn(
  z.string(),
  z.number().min(0).max(100),
  (name, age) =>
    `Hello ${name.toUpperCase()} you are ${age.toFixed(1)} years old`
);

greet("alex", 42); // "Hello alex you are 42 years old"
greet(null, 42); // tsc compiler error
greet(null as any, 42); // myzod runtime error
greet("alex", -10); // myzod runtime error

You can also define custom parsers. A parser is just an object with a parse function. The parse function's return type will be used to infer its corresponding function argument type.

const DirectionParser = {
  parse(value: unknown): "left" | "right" {
    if (value !== "left" && value !== "right") {
      throw new Error("Invalid direction!");
    }
    return value as "left" | "right";
  },
};

const turn = Zfn(DirectionParser, (direction) => {
  // direction's inferred type is `"left" | "right"`
});

Usage

Two functions are available:

  • Zfn - Takes any number of parsers followed by a function. Returns a new function with the same signature as the input function but with arguments that are validated using the schemas.
  • isZfn - A utility function for checking if a value is a Zfn instance.
0.0.16

3 years ago

0.0.15

3 years ago

0.0.14

3 years ago

0.0.13

3 years ago

0.0.12

3 years ago

0.0.11

3 years ago

0.0.10

3 years ago

0.0.9

3 years ago

0.0.7

3 years ago

0.0.6

3 years ago

0.0.5

3 years ago

0.0.4

3 years ago

0.0.3

3 years ago

0.0.2

3 years ago

0.0.1

3 years ago