New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

iron-enum

Package Overview
Dependencies
Maintainers
0
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

iron-enum

Rust like enums for Typescript

  • 1.0.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
16
increased by100%
Maintainers
0
Weekly downloads
 
Created
Source

Iron Enum

Finally Rust like enums in Typescript!

  • Ergonomic AF!
  • Fully type safe!
  • Only 500 bytes!

| Github | NPM | JSR |

Typescript enums only provide simple variants:

enum Shape {
    Square,
    Circle
}

But what if you wanted to provide data for each variant that is context specific? Well now you can!

import { IronEnum } from "iron-enum";

const ShapeEnum = IronEnum<{
    Empty: {},
    Square: { width: number, height: number },
    Circle: { radius: number }
}>();

const exampleShape = ShapeEnum.Square({width: 22, height: 50});

// Supports matching
exampleShape.match({
    Empty: () => {
        // runs if the shape is empty
    },
    Square: ({width, height}) => {
        // runs if the shape is square
    },
    Circle: ({radius}) => {
        // runs if the shape is circle
    }
});

// Supports fallback cases and returns through match
const result = exampleShape.match({
    Square: ({width, height}) => {
        // runs if the shape is square
        return width;
    },
    _: () => {
        // runs if it's anything but a square
        return "hello"
    }
});
// result type is inherited from match arm return types.
// typeof result == number | string

if (exampleShape.if.Square()) {
    // runs if the shape is a square
}

if (exampleShape.ifNot.Square()) {
    // runs if the shape is NOT a square
}

console.log(exampleShape.unwarp())
// output: ["Square", { width: 22, height: 50 }]

// this method will only allow ShapeEnum variants as an argument
const someFn = (onlyShapeEnum: typeof ShapeEnum._self.prototype) => {

}

Just like in Rust, the .match(...) keys must contain a callback for each variant OR provide a fallback method with a _ property. Failing this constraint leads to a type error.

FAQs

Package last updated on 10 Oct 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc