Skip to content

Custom Types #3

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';constIncrement=Type.custom('Increment');constDecrement=Type.custom('Decrement');letvalue=0;constmsg=Increment();Type.matchOn(msg,{[Increment](){value=value+1;},[Decrement](){value=value-1;},});console.log(value);// 1

Parameters

import{Type}from'wool/core';constSetValue=Type.custom('SetValue',Type.int);constmsg=SetValue(42);Type.matchOn(msg,{// ...[SetValue](newValue){value=newValue;},});console.log(value);// 42
import{String,Type}from'wool/core';constSetGreeting=Type.custom('SetGreeting',Type.string,Type.int)letvalue='Hi';constmsg=SetGreeting('Hello',3);Type.matchOn(msg,{[SetGreeting](greeting,times){value=String.repeat(greeting,times);},});console.log(value);// "HelloHelloHello"

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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