Eject enums from your TypeScript codebase.
eject-enum is a code rewriting tool for TypeScript codebases that
rewrites each TypeScript enum in your codebase to
the safer alternative.
Before rewriting:
/**
* Signals of traffic light.
*/
export enum TrafficLight {
/** Stop. */
Red,
/** Stop unless you can't do so safely. */
Yellow,
/** Go. */
Green,
}
After rewriting:
/**
* Signals of traffic light.
*/
export const TrafficLight = {
/** Stop. */
Red: 0,
/** Stop unless you can't do so safely. */
Yellow: 1,
/** Go. */
Green: 2,
} as const;
export type TrafficLight = (typeof TrafficLight)[keyof typeof TrafficLight];
It is recommended to run code formatting tools after rewriting by eject-enum, as it doesn't consider any code formatting configurations of your project when rewriting.
You can execute eject-enum as a CLI tool:
# npm
npx eject-enum [options...]
# pnpm
pnpx eject-enum [options...]
# Bun
bunx eject-enum [options...]
# Deno >=2.6 (cf. https://deno.com/blog/v2.6#run-package-binaries-with-dx)
dx eject-enum [options...]
CLI Options:
# If no targets are specified, it tries to use `tsconfig.json`
# in the current directory as the default target.
npx eject-enum
# Rewrite all files in projects specified by tsconfigs.
npx eject-enum path/to/tsconfig.json path/to/tsconfig2.json
# Rewrite all Typescript files under the `src` and `test` directories,
# except files under the `src/foo` directory.
npx eject-enum "src/**/*.ts" "test/**/*.ts" --exclude "src/foo/**/*.ts"
You can use eject-enum as a library from your scripts as well.
npm install --save-dev eject-enum
import { ejectEnum, EjectEnumTarget } from "eject-enum";
// Rewrite all files in projects specified by paths to tsconfigs.
ejectEnum(
EjectEnumTarget.projects([
"path/to/tsconfig.json",
"path/to/tsconfig2.json",
]),
);
// Rewrite all Typescript files under the `src` and `test` directories
// except files under the `src/foo` directory.
ejectEnum(
EjectEnumTarget.srcPaths({
include: ["src/**/*.ts", "test/**/*.ts"],
exclude: ["src/foo/**/*.ts"],
}),
);
if, while, switch).eject-enum have some limitations about code rewriting. They originate from limitations of the TS Compiler API/ts-morph.