|
| 1 | +# Typed Env |
| 2 | + |
| 3 | +A strongly-typed, 0-dependency environment variable parser for Typescript! |
| 4 | + |
| 5 | +## Why is this useful |
| 6 | + |
| 7 | +Many services use environment variables for runtime configuration, anything from the current |
| 8 | +environment or logging verbosity, to things like API keys and secrets. But many times, these |
| 9 | +environment variables are unvalidated and naively parsed from strings when needed. |
| 10 | + |
| 11 | +This library aims to allow you to define environment variables in a more type-safe way. Take this |
| 12 | +example: |
| 13 | + |
| 14 | +```ts |
| 15 | +const environment = process.env.ENVIRONMENT; |
| 16 | + |
| 17 | +const makePayment = (amount: bigint) => { |
| 18 | + if (environment === 'prod') { |
| 19 | + makeRealPayment(amount); |
| 20 | + } else { |
| 21 | + makeMockPayment(amount); |
| 22 | + } |
| 23 | +}; |
| 24 | +``` |
| 25 | + |
| 26 | +What if you configured your server with `ENVIRONMENT=production` instead of `ENVIRONMENT=prod`? |
| 27 | +Suddenly, all your users are getting free products because you're making mock payments instead of |
| 28 | +real ones! |
| 29 | + |
| 30 | +If you'd used TypedEnv instead, you'd get this |
| 31 | + |
| 32 | +```ts |
| 33 | +const env = TypedEnv({ |
| 34 | + ENVIRONMENT: EnumVar({options: ['dev', 'staging', 'production']}), |
| 35 | +}); |
| 36 | + |
| 37 | +const makePayment = (amount: bigint) => { |
| 38 | + if (env.ENVIRONMENT === 'prod') { |
| 39 | + // TypeError! |
| 40 | + // `This condition will always return 'false' since |
| 41 | + // the types '"dev" | "staging" | "production"' and |
| 42 | + // '"prod"' have no overlap.` |
| 43 | + return makeRealPayment(amount); |
| 44 | + } else { |
| 45 | + return makeFakePayment(amount); |
| 46 | + } |
| 47 | +}; |
| 48 | +``` |
| 49 | + |
| 50 | +## What types are supported? |
| 51 | + |
| 52 | +Currently, strings, integers, and enums are supported, although you can define your own custom type |
| 53 | +using the `Declaration<T>` type |
| 54 | + |
| 55 | +```ts |
| 56 | +export type Declaration<T> = { |
| 57 | + variable?: string; // The name of the environment variable; defaults to match the key if not specified |
| 58 | + parser: Parser<T>; // A function (value: string) => T |
| 59 | +}; |
| 60 | +``` |
0 commit comments