Skip to content

Custom Types #3

@lsjroberts

Description

@lsjroberts

Custom types are also known as "union types", "tagged unions" and "algebraic data types".

While typescript provides a way to have compile-time union types, they are no longer available at runtime, which means they can't be used for active behaviours (such as messages in wool/browser).

Basic usage

import { Type } from 'wool/core';

const Increment = Type.custom('Increment');
const Decrement = Type.custom('Decrement');

let value = 0;

const msg = Increment();

Type.matchOn(msg, {
  [Increment]() { value = value + 1; },
  [Decrement]() { value = value - 1; },
});

console.log(value);
// 1

Parameters

import { Type } from 'wool/core';

const SetValue = Type.custom('SetValue', Type.int);

const msg = SetValue(42);

Type.matchOn(msg, {
  // ...
  [SetValue](newValue) { value = newValue; },
});

console.log(value);
// 42
import { String, Type } from 'wool/core';

const SetGreeting = Type.custom('SetGreeting', Type.string, Type.int)

let value = 'Hi';

const msg = SetGreeting('Hello', 3);

Type.matchOn(msg, {
  [SetGreeting](greeting, times) {
    value = String.repeat(greeting, times);
  },
});

console.log(value);
// "HelloHelloHello"

Metadata

Metadata

Assignees

No one assigned

    Labels

    discussionIdeas open for discussion

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions