Native TypeScript Enums #28179
Unanswered
axelrindle
asked this question in
Feature Requests
Replies: 1 comment
|
For the meantime, I created the following script (ChatGPT did, actually) to replace the union types with enums: import { readFileSync, writeFileSync } from 'node:fs'
import { globSync } from 'glob'
function removeIndentation(input: string): string {
return input.split('\n')
.map(s => s.substring(6))
.join('\n')
.trim()
}
// Function to convert union types to enums
function convertUnionToEnums(input: string) {
// Regex to locate the Enums object within the public namespace and capture its content
const enumsRegex = /Enums:\s*{([^}]*)}/g
let enumsMatch = enumsRegex.exec(input)
if (!enumsMatch) {
throw new Error('Enums object not found')
}
let enumsContent = removeIndentation(enumsMatch[1])
const unionRegex = /(\w+):\s*((?:"[^"]*"(?:\s*\|\s*"[^"]*")*)|(?:\n\s*\|\s*"[^"]*")+)/g
const matches = [...enumsContent.matchAll(unionRegex)]
let enums = ''
// Extracting the union types and generating enums
for (let match of matches) {
const enumName = match[1]
const unionValues = match[2]
.split('|')
.map(val => val.trim().replace(/"/g, ''))
.filter(Boolean)
// Generate Enum
enums += `export enum ${enumName} {\n`
unionValues.forEach(value => {
enums += ` '${value}',\n`
})
enums += '}\n\n'
// Replace union type with keyof typeof Enum in enumsContent
const unionRegex = new RegExp(`(\\b${enumName}\\b):\\s*((?:"[^"]*"(?:\\s*\\|\\s*"[^"]*")*)|(?:\\n\\s*\\|\\s*"[^"]*")+)`, 'g')
enumsContent = enumsContent.replace(unionRegex, `$1: keyof typeof ${enumName}`)
}
// Replace the original Enums content with updated enumsContent in the inputType
const updatedType = input.replace(enumsMatch[1], enumsContent)
return enums + updatedType
}
const files = globSync('*/**/db.ts')
const input = readFileSync('db.ts')
for (const file of files) {
// Generate the updated TypeScript code
const output = convertUnionToEnums(input.toString('utf8'))
// Write the output to a file (optional)
writeFileSync(file, output)
} |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
While TypeScript codegen is working fine, I'd like to suggest the usage of Native TypeScript Enums. This would allow users to use the Enum for validation purposes, e.g. using
zod.An example:
Then I could do the following with
zod:All reactions