@scale-codec/enum
TypeScript icon, indicating that this package has built-in type declarations

2.1.1 • Public • Published

@scale-codec/enum build status version license

Small tagged-union library for TypeScript.

Features

  • Type narrowing and exhaustiveness check (due to the library following TypeScript's discriminated union pattern)
  • Creation of type-safe variants
  • Type inference during variant creation

Installation

Available on NPM:

npm i @scale-codec/enum

Example

Enum in Rust:

enum Event {
  PageLoaded,
  KeyPress(String),
  MouseClick { x: u32, y: u32 }
}

Enum in TypeScript:

import { Enumerate, variant } from '@scale-codec/enum'

// Define the enum
type Event = Enumerate<{
  PageLoaded: []
  KeyPress: [string]
  MouseClick: [{ x: number; y: number }]
}>

// Construct an actual value
const event1: Event = variant('KeyPress', '<enter>')
const event2 = variant<Event>('MouseClick', { x: 5, y: 10 })
const event3 = variant<Event>('PageLoaded')

// Access the content
if (event1.tag === 'MouseClick') {
  // Types are narrowed
  const { x, y } = event1.content
}

API

@scale-codec/enum API

Readme

Keywords

Package Sidebar

Install

npm i @scale-codec/enum

Weekly Downloads

140

Version

2.1.1

License

Apache-2.0

Unpacked Size

24.8 kB

Total Files

7

Last publish

Collaborators

  • soramitsu-admin