Type-safe environment variables with runtime validation
npm install @russellfrrr/typed-envprocess.env so errors happen
process.env parsing
string, number, and boolean parsers
optional() and default() helpers
process.env
bash
npm install typed-env
`
Usage
`ts
import { createEnv, string, number, boolean } from 'typed-env';
const env = createEnv({
NODE_ENV: string(),
PORT: number().default(3000),
DEBUG: boolean().optional(),
DATABASE_URL: string(),
});
// env is fully typed:
// {
// NODE_ENV: string;
// PORT: number;
// DEBUG: boolean | undefined;
// DATABASE_URL: string;
// }
`
Parsers
$3
- Required by default
- Use .optional() or .default(value) to adjust behavior
$3
- Parses with Number() and throws on NaN
$3
- Accepts only "true" and "false"
$3
Restricts an environment variable to a fixed set of allowed string values.
`ts
import { createEnv, enum_ } from 'typed-env';
const env = createEnv({
NODE_ENV: enum_(['dev', 'prod', 'test']),
});
// type of env.NODE_ENV:
// 'dev' | 'prod' | 'test'
`
Optional and Default
`ts
const env = createEnv({
OPTIONAL_VALUE: string().optional(),
PORT: number().default(3000),
});
`
Errors
When a required variable is missing or invalid, createEnv throws an Error with a helpful message like:
- Missing environment variable: PORT
- Invalid number for PORT
- Invalid boolean for DEBUG
Testing
This project includes automated tests using Vitest to verify
runtime behavior of all parsers.
`bash
npm test
`
API
$3
Parses process.env using the provided schema and returns a typed object.
$3
Each parser implements:
- parse(value: string | undefined, key: string): T
- optional(): Parser
- default(value: T): Parser