0.0.29 • Published 9 months ago

variant-ts v0.0.29

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
9 months ago

Variant-ts

Variant, Option and Result types for Typescript

Variants

import { Variant, variant } from "variant-ts";

type Connection =
  | Variant<"IPV4", [number, number, number, number]>
  | Variant<"IPV6", string>;

let ip = variant<Connection>("IPV4", [127, 0, 0, 1]);

Variants are very handy when used together with reducers:

import { Variant, variant, pattern } from "variant-ts";
import { match } form "ts-pattern";

type State = {
    name: string,
    age: number,
    messages: string[]
}

type Action =
    Variant<"ChangeName", string>
    | Variant<"ChangeAge", number>
    | Variant<"AddMessage", string>

function reducer(state: State, action: Action): State {
    return match(action)
        .with(pattern("ChangeName"), res => { return { name: res.val, ...state } })
        .with(pattern("ChangeAge"), res => { return { age: res.val, ...state } })
        .with(pattern("AddMessage"), res => { return { messages: [...state.messages, res.val], ...state } })
        .exhaustive()
}

let initial_state = {
    name: "John Doe",
    age: 24,
    messages: ["Hey, how are you?", "See you"]
}

let new_state = reducer(initial_state, variant<Action>("AddMessage", "Variants are awesome"))

Options

import { none, some } from "variant-ts";

const one = some("foo");
const two = none();

const three = one.map((x) => x.concat("bar"));
const four = two.map((x) => x.concat("bar"));

expect(three.val).to.equal("foobar");
expect(four.val).to.equal(undefined);

Results

import { err, ok } from "variant-ts";

const one = ok("foo");
const two = err("error");

const three = one.map((x) => x.concat("bar"));
const four = two.map((x) => x.concat("bar"));

expect(three.val).to.equal("foobar");
expect(four.val).to.equal("error");
0.0.25

9 months ago

0.0.26

9 months ago

0.0.27

9 months ago

0.0.28

9 months ago

0.0.29

9 months ago

0.0.22

1 year ago

0.0.23

1 year ago

0.0.24

1 year ago

0.0.21

1 year ago

0.0.20

1 year ago

0.0.19

1 year ago

0.0.18

1 year ago

0.0.17

1 year ago

0.0.15

1 year ago

0.0.14

1 year ago

0.0.13

2 years 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