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});
exampleShape.match({
Empty: () => {
},
Square: ({width, height}) => {
},
Circle: ({radius}) => {
}
});
const result = exampleShape.match({
Square: ({width, height}) => {
return width;
},
_: () => {
return "hello"
}
});
if (exampleShape.if.Square()) {
}
if (exampleShape.ifNot.Square()) {
}
console.log(exampleShape.unwarp())
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.