Skip to content

Commit

Permalink
Merge pull request #14 from pandaniell/feat/union
Browse files Browse the repository at this point in the history
feat: allow union type generation
  • Loading branch information
benawad authored Mar 5, 2021
2 parents 7ad9fe0 + 937a3f1 commit 571424f
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
21 changes: 18 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ STRIPE_ACCESS_TOKEN=qoi120wqe

And generates a `.d.ts` file

```
```typescript
declare namespace NodeJS {
export interface ProcessEnv {
SESSION_SECRET: string;
Expand All @@ -20,13 +20,28 @@ declare namespace NodeJS {

Now `process.env.SESSION_SECRET` will autocomplete and be type-safe.

## Usage
If you want to generate a union instead of string type, add an inline comment to your `.env` file:

```
NODE_ENV = "production" # production | development
```

```typescript
declare namespace NodeJS {
export interface ProcessEnv {
NODE_ENV: "production" | "development";
}
}
```

## Usage

```bash
npx gen-env-types path/to/.env
```

## Options

```
-V, --version Show version number
-h, --help Show usage information
Expand All @@ -36,6 +51,6 @@ npx gen-env-types path/to/.env

## Example with options

```
```bash
npx gen-env-types .env -o src/types/env.d.ts -e .
```
12 changes: 11 additions & 1 deletion gen-env-types.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,17 @@ function writeEnvTypes(envString, path) {
${envString
.split("\n")
.filter((line) => line.trim() && line.trim().indexOf("#") !== 0)
.map((x, i) => `${i ? " " : ""}${x.trim().split("=")[0]}: string;`)
.map((x, i) => {
const union = x.split('"').pop().trim()
if (union) {
const stringLiterals = union.replace("#", "").split(" | ")
return `${i ? " " : ""}${x.split("=")[0]}: ${stringLiterals.map((text) => `"${text.trim()}"`).join(" | ")};`
}
return `${i ? " " : ""}${x.trim().split("=")[0]}: string;`
})
.join("\n")}
}
}
Expand Down

0 comments on commit 571424f

Please sign in to comment.