dotenv-types

A TypeScript library for type-safe environment variable parsing and validation.

Features

  • Type-safe environment variable parsing
  • Support for multiple variable types: string, number, boolean, port, email, url, json, enum
  • Schema-based validation
  • Automatic type inference
  • Cleaned environment variables output

Installation

npm install dotenv-types

Usage

import { parseEnvSchema } from 'dotenv-types';

const schema = {
  PORT: { type: 'port', required: true },
  DB_HOST: { type: 'string', required: true },
  DB_PORT: { type: 'port', required: true },
  DEBUG: { type: 'boolean', default: false },
  LOG_LEVEL: { type: 'enum', options: ['debug', 'info', 'warn', 'error'], default: 'info' }
};

const result = parseEnvSchema(schema);

if (result.isValid) {
  console.log('Cleaned env:', result.cleanedEnv);
} else {
  console.log('Validation errors:', result.errors);
}

API

parseEnvSchema(schema)

Parses environment variables according to the provided schema.

Parameters:

  • schema: An object defining expected environment variables

Returns: ValidationResult with:

  • isValid: Boolean indicating if all validations passed
  • errors: Array of validation errors
  • cleanedEnv: Object with cleaned/typed environment variables

Supported Types

  • string - Any string value
  • number - Numeric values
  • boolean - true/false, 1/0, yes/no
  • port - Valid port numbers (1-65535)
  • email - Valid email addresses
  • url - Valid URLs
  • json - Valid JSON strings
  • enum - Value must match one of the provided options

License

MIT

Description
A CLI tool that validates .env files against a schema and auto-generates TypeScript interfaces for type-safe environment variables.
Readme MIT 99 KiB
Languages
TypeScript 96.3%
JavaScript 3.7%