enum-ts
Place this definition somewhere in your project:
typescript
/**
* This special type can help generate pattern matchers for you!
* Just use it as so:
*
* type Result<Ok, Err> = Enum<{
* Ok: Ok,
* Err: Err,
* }>
*/
export type Enum<T extends { [Variant: string]: any }> = {
}[keyof T];
Now whenever you write a type with Enum
definition at the root of a file (cannot be nested in another block), then
enum-ts
will be able to generate exhaustive pattern matchers and constructor code for you!
This is currently just an executable you can install through compiling through cargo, or use by installing through npm (soon).
sh
cargo install enum-ts
Then, you can test it out with one of the examples in tests/
or in this README:
sh
cat ./tests/result.ts | enum-ts
Which will print the generated enum matcher helpers!
```sh enum-ts
cat my-file.ts | enum-ts
enum-ts --write .
enum-ts .
--write
flag.```
Input
typescript
type Result<O, E> = Enum<{
Ok: O;
Err: E;
}>;
Generated
typescript
export namespace Result {
export function Ok<O, E>(contents: O): Result<O, E> {
return ["Ok", contents];
}
export function Err<O, E>(contents: E): Result<O, E> {
return ["Err", contents];
}
export function apply<O, E, R>(fns: {
Ok(content: O): R;
Err(content: E): R;
}): (value: Result<O, E>) => R {
return function matchResultApply([name, contents]) {
// @ts-ignore
return fns[name](contents);
};
}
export function match<O, E, R>(
value: Result<O, E>,
fns: {
Ok(content: O): R;
Err(content: E): R;
}
): R {
return apply(fns)(value);
}
}
Usage
typescript
const res = Result.Ok<string, any>("okay value");
Result.match(res, {
Ok(value) {
// do something with value
},
Err(err) {
// do something with err
},
});
Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.