Convert Enums to Union types
- Input:
enum Direction {
Up = 'UP',
Down = 'DOWN',
}
- Output without helperDir option:
export const Direction = {
Up: "UP",
Down: "DOWN",
} as const;
export type Direction = (typeof Direction)[keyof typeof Direction];
- Output with helperDir option:
object-values.ts
export type ObjectValues<T> = T[keyof T];
import { ObjectValues } from "./types/object-values";
export const Direction = {
Up: "UP",
Down: "DOWN",
} as const;
export type Direction = ObjectValues<typeof Direction>;
tsx ${pathToLibrary}/enum2union/src/index.ts --project-files='./src/**/*.{tsx,ts}' --helper-dir='src/types/helpers'
import { transform } from './src/index.ts';
transform({
projectFiles: './src/**/*.{tsx,ts}',
helperDir: './src/types',
});
Typescript has unions, so are enums redundant? - Stack Overflow
Enums considered harmful - YouTube
Enums are MISUNDERSTOOD (not terrible): Josh Goldberg, typescript-eslint maintainer - YouTube
https://www.typescriptlang.org/docs/handbook/enums.html#objects-vs-enums
Alternatives to enums in TypeScript
benjlevesque/codemod-enum-to-union doesn't have ObjectValues helper, the code is formatted worse
cartant/eslint-plugin-etc: More general-purpose (TypeScript-related) ESLint rules
shian15810/eslint-plugin-typescript-enum: ESLint rules for TypeScript enums.
https://typescript-eslint.io/linting/troubleshooting/#how-can-i-ban-specific-language-feature
- transform string enum to union
- add helper ObjectValues
- insert import of helper after all imports
- fix insertStatements dsherret/ts-morph#1192
- improve formatting by adding space after type and const declaration
- support import alias
- use ts for resolving import microsoft/TypeScript#50187
- publish as package