Small TS library to type and safely handle `serde` JSON serializations of Rust enums.

Overview

rustie-ts

TypeScript library with helper types and functions to type-safely handle Rust's serde JSON serialization of Enums. It can also be used standalone to implement enums/tagged-unions in TypeScript with plain objects.

Installation

npm install --save rustie
# OR
yarn add rustie

Example

import type { Enum } from "rustie"
import { flatten_enum, flatten_enum_f, match, if_let } from "rustie"

type Stuff = Enum<{
  Color: Color
  BW: BW
}>

interface Color {
  r: number
  g: number
  b: number
}

interface BW {
  value: boolean
}

const a: Stuff = { Color: { r: 10, g: 20, b: 35 } }
const b: Stuff = { BW: { value: true } }

const all: Stuff[] = [a, b]

for (const elem of all) {
  console.log(`Matching with map_enum...`)
  match(elem)({
    Color: (color) => console.log(color.r + color.g + color.b),
    BW: (bw) => console.log(bw.value),
  })
}

for (const elem of all) {
  console.log(`Matching with if_let...`)
  if_let(elem)("Color")((color) =>
    console.log(`This is color: R:${color.r} G:${color.g} B:${color.b}`)
  )(() => console.log(`This is not color: ${elem}`))
}


for (const _elem of all) {
  console.log(`Matching with flatten_enum...`)
  const variant = flatten_enum(_elem)
  switch (variant.$) {
    case "Color":
      const color = variant.val
      console.log(`R: ${color.r}, G: ${color.b} + B: ${color.g}`)
      // console.log(`${color.value}`) // Type check FAILS
      break
    case "BW":
      const bw = variant.val
      console.log(`VALUE: ${bw.value}`)
      // console.log(`${bw.r}`) // Type check FAILS
      break
  }
}

for (const elem of all) {
  console.log(`Matching with flatten_enum_f...`)
  flatten_enum_f(elem)(({ $, val }) => {
    switch ($) {
      case "Color":
        console.log(`R: ${val.r}, G: ${val.b} + B: ${val.g}`)
        // console.log(`${val.v}`) // Type check FAILS
        break
      case "BW":
        console.log(`VALUE: ${val.value}`)
        // console.log(`${val.r}`) // Type check FAILS
        break
    }
  })
}
You might also like...

A type programming language which compiles to and interops with type-level TypeScript

Prakaar Prakaar (hindi for "type") is a type programming language which compiles to and interops with type-level TypeScript. Prakaar itself is also a

Sep 21, 2022

100% type-safe query builder for node-postgres :: Generated types, call any function, tree-shakable, implicit type casts, and more

⚠️ This library is currently in alpha. Contributors wanted! tusken Postgres client from a galaxy far, far away. your database is the source-of-truth f

Dec 29, 2022

Type predicate functions for checking if a value is of a specific type or asserting that it is.

As-Is Description As-Is contains two modules. Is - Type predicates for checking values are of certain types. As - Asserting values are of a certain ty

Feb 10, 2022

🐬 A simplified implementation of TypeScript's type system written in TypeScript's type system

🐬 A simplified implementation of TypeScript's type system written in TypeScript's type system

🐬 HypeScript Introduction This is a simplified implementation of TypeScript's type system that's written in TypeScript's type annotations. This means

Dec 20, 2022

A transpiler from golang's type to typescript's type for collaboration between frontend & backend.

A transpiler from golang's type to typescript's type for collaboration between frontend & backend.

go2type go2type.vercel.app (backup site) A typescript transpiler that convert golang's type to typescript's type. Help front-end developer to work fas

Sep 26, 2022

This is just a script I put together to check and notify me via email (MailGun) when there's an earlier date before my initial appointment date. It doesn't handle rescheduling.

This is just a script I put together to check and notify me via email (MailGun) when there's an earlier date before my initial appointment date. It doesn't handle rescheduling.

US-visa-appointment-notifier This is just a script I put together to check and notify me via email (MailGun) when there's an earlier date before my in

Jan 4, 2023

A simple handle tap and hold action for Svelte/SvelteKit.

Svelte Tap Hold Minimalistic tap and hold component for Svelte/SvelteKit, see demo here. Installation // Using Yarn to install yarn add --dev svelte-t

Dec 8, 2022

Some process handle JavaScript function parameter.

Function parameter handle or paremeter error control Example 1: Just checking if all arguments were passed / defined. const required = (name) = {

Mar 14, 2022

A set of useful helper methods for writing functions to handle Cloudflare Pub/Sub messages (https://developers.cloudflare.com/pub-sub/)

pubsub A set of useful helper methods for writing functions to handle Cloudflare Pub/Sub messages. This includes: A isValidBrokerRequest helper for au

Dec 4, 2022
Releases(v0.2.0)
  • v0.2.0(Aug 1, 2022)

    • export tag; renaming functions 0517de0
    • add Option ec44f27
    • better examples first on README 48876ae

    https://github.com/steinerkelvin/rustie-ts/compare/v0.1.2...v0.2.0

    Source code(tar.gz)
    Source code(zip)
Owner
Kelvin Steiner Santos
computer nerd · descentralization-ist · FOSS · #bitcoin · https://linktr.ee/kelvinss
Kelvin Steiner Santos
Experimental proxy and wrapper for safely embedding Web Archives (warc.gz, wacz) into web pages.

warc-embed-netlify ??️ Experimental proxy and wrapper for safely embedding Web Archives (.warc.gz, .wacz) into web pages. This particular implementati

Harvard Library Innovation Laboratory 6 Sep 1, 2022
A typescript transform that converts exported const enums into object literal.

ts-transformer-optimize-const-enum A typescript transformer that convert exported const enum into object literal. This is just like the one from @babe

Fonger 22 Jul 27, 2022
JavaScript enums using proxies.

enum-xyz JavaScript enums using proxies. Based on this tweet Install $ npm install enum-xyz --save Usage Strings import Enum from 'enum-xyz' const {

Chase Fleming 38 Oct 22, 2022
A TypeScript namespace declaration for KeyboardEvent.key strings, just in case your code is allergic to enums.

ts-key-namespace A TypeScript namespace declaration for KeyboardEvent.key strings, just in case you prefer namespaces to enums. Largely based on ts-ke

Daniel Soohan Park 3 Apr 5, 2022
JCS (JSON Canonicalization Scheme), JSON digests, and JSON Merkle hashes

JSON Hash This package contains the following JSON utilties for Deno: digest.ts provides cryptographic hash digests of JSON trees. It guarantee that d

Hong Minhee (洪 民憙) 13 Sep 2, 2022
Package fetcher is a bot messenger which gather npm packages by uploading either a json file (package.json) or a picture representing package.json. To continue...

package-fetcher Ce projet contient un boilerplate pour un bot messenger et l'executable Windows ngrok qui va permettre de créer un tunnel https pour c

AILI Fida Aliotti Christino 2 Mar 29, 2022
A small javascript DOM manipulation library based on Jquery's syntax. Acts as a small utility library with the most common functions.

Quantdom JS Quantdom is a very small (about 600 bytes when ran through terser & gzipped) dom danipulation library that uuses a Jquery like syntax and

Sean McQuaid 7 Aug 16, 2022
An itty library to handle common time-related things for your API needs.

Tiny (~500 bytes) time math library for making date handling and TTLs within your APIs beautiful. Features Tiny @ ~500 bytes gzipped total, and tree-s

Kevin R. Whitley 8 Jan 2, 2023
Combine type and value imports using Typescript 4.5 type modifier syntax

type-import-codemod Combines your type and value imports together into a single statement, using Typescript 4.5's type modifier syntax. Before: import

Ian VanSchooten 4 Sep 29, 2022
🧬 A type builder for pagination with prisma and type-graphql.

?? Prisma TypeGraphql Pagination Prisma TypeGraphql Pagination builds prisma pagination types for type-graphql. import { ... } from 'type-graphql'

Arthur Fiorette 2 Apr 21, 2022