@scale-codec/enum
v2.1.1
Published
Simple JavaScript abstraction around Rust Enums
Downloads
595
Readme
@scale-codec/enum
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
}