npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

typed-env-loader

v1.0.1

Published

A parser of environment variables to typed values

Readme

typed-env-loader

Test and build

Typed environment variables and values, and intellisense helper.

Mainly for typescript source codes.

Install

You can use typed-env-loader with dotenv, and we recoment it:

npm install dotenv typed-env-loader

Remember to load dotenv in your script:

// for javascript
require('dotenv').config();
// for typescript
import 'dotenv/config';

Usage

In the simple case, create a configuration file and use loadConfig function to parse your environment variables:

// "config.ts"
import 'dotenv/config';
import { loadConfig } from 'typed-env-loader';

export const Config = loadConfig({
  port: { name:'PORT', type:'number', defaultValue: 80 },
  // ...
});

// -----------------
// "main.ts"
import { Config } from './config';
console.log(`Port: ${Config.port}`);

// After that you have access to "Config.port" and other configurations defined.
// And ( typeof Config.port === 'number' ) is "true", the value was converted to javascript 'number' type.

You can split your configurations in parts with the defineConfig function.
This functions does nothing but will let intellisense aware of the typings.

// "config.ts"
import 'dotenv/config';
import { loadConfig, defineConfig } from 'typed-env-loader';

// "defineConfig" receives the same object than "loadConfig"
export const ConfigPresetDatabase = defineConfig({
    databaseUrl:        { name: 'DATABASE_URL',         type: 'string', defaultValue: '' },
    databaseUsername:   { name: 'DATABASE_USERNAME',    type: 'string', defaultValue: '' },
    databasePassword:   { name: 'DATABASE_PASSWORD',    type: 'string', defaultValue: '' },
});
export const ConfigPresetServer = defineConfig({
    serverPort:         { name: 'PORT',                 type: 'number', defaultValue: 5000 },
    serverRouteContext: { name: 'ROUTE_CONTEXT',        type: 'string', defaultValue: '' },
    serverCookiesSecure: { name: 'SERVER_COOKIES_SECURE', type: 'boolean', defaultValue: false },
});
export const ConfigPresetSMTP = defineConfig({
    smtpHost:           { name: 'SMTP_HOST',            type: 'string', defaultValue: '' },
    smtpPort:           { name: 'SMTP_PORT',            type: 'number', defaultValue: 587 },
    smtpUser:           { name: 'SMTP_USER',            type: 'string', defaultValue: '' },
    smtpPass:           { name: 'SMTP_PASS',            type: 'string', defaultValue: '' },
});

export const Config = loadConfig({
  ...ConfigPresetDatabase,
  ...ConfigPresetServer,
  ...ConfigPresetSMTP,

  // and define others configs
  another: { name:'ANOTHER', type:'string', defaultValue: 'default string' },
  // ...
});

Parameters and configurations

  • loadConfig(config: T, envObjArr?: Record<string, any>[] | Record<string, any> | null, mergeConfig?: any, extraConfig?: Partial<EnvExtraConfig> | null): R
    Loads configuration from environment variables, or the envObjArr informed.
    • config: the configuration definition object. Need to follow the type EnvDefinition, that is an object where the keys will be the key in the loaded configuration (the returned value of this function) and the values as configuration definitions of type EnvConfig.
      Possible configurations of EnvConfig are:

      • name: defaults to the key name
        The name of the configuration on the environment or the envObjArr param. If not set, the will be the same as the key of this line:
      loadConfig({
        PORT: { type:'number' }, // "name" will be "PORT"
      })
      • type: defaults to auto
        Type of the value to parse. Possible values are in EnvConfigTypeField type:
        'auto' , 'boolean' , 'number' , 'string', 'auto[]' , 'boolean[]' , 'number[]' , 'string[]'
        Values with [] in the end will be loaded as arrays.
        The auto type will try to guess the type, but will not find arrays automaticaly.

      • separator: defaults to /\s*(?:(?<!\\)[,;])+\s*/g
        Separator to use on split() function when loading arrays. Can be a string or a RegExp.
        The default RegExp will use , and ; characters, and use backslash \ to escape the separator characters.

      loadConfig({
        TEXTS: { type:'string[]' }, 
        // with "TEXTS" env == "Hello world\, friends! , Lets develop!;Lovely Devs"
        // "TEXTS" will load "['Hello world, friends!', 'Lets develop!', 'Lovely Devs']" 
      })

      If you want to define your separator, consider using the lookbehind of this default value to have the same escape capabilities.

      • defaultValue: defaults to none
        The default value that will be loaded if the environment doenst have a variable defined.

      • choices: defaults to none
        A list of acceptable values for this configuration.
        If the type is an array then all values parsed need to be one of these items.

      // loads fine
      loadConfig({
        ENV: { type:'string', choices:['dev','stage','prod'] }, 
        // with "ENV" env == "prod"
        LOG_LEVEL: { type:'string', choices:['info','warn','error'] }, 
        // with "LOG_LEVEL" env == "info"
        PLUGINS: { type:'string[]', choices:['feat01','extra02','another03'] }, 
        // with "PLUGINS" env == "feat01, another03"
      })
          
      // ---
      // an error will be thrown in that cases
      loadConfig({
        ENV: { type:'string', choices:['dev','stage','prod'] }, 
        // with "ENV" env == "uat"
        LOG_LEVEL: { type:'string', choices:['info','warn','error'] }, 
        // with "LOG_LEVEL" env == "debug"
        PLUGINS: { type:'string[]', choices:['feat01','extra02','another03'] }, 
        // with "PLUGINS" env == "feat01, super04"
      })
      • readonly: defaults to true
        If the load configuration need to define the property to readonly.
      const Config = loadConfig({
        ENV: { type:'string', readonly: true },
        // with "ENV" env == "prod"
      })
      Config.ENV = 'dev'; // will throw an Error
      
      // ---
      const Config02 = loadConfig({
        ENV: { type:'string', readonly: false },
        // with "ENV" env == "prod"
      })
      Config02.ENV = 'dev'; // after that "Config02.ENV" have the value "dev"
    • envObjArr: an object to load configurations from. Defaults to process.env. An array of objects can be set to load from them.

    • mergeConfig: the object to where the loaded configurations will be put in. This is the same object returned by the function. If not set then a new object will be created and returned.

    • extraConfig: configurations for general behavior of loadConfig function. Acceptable configurations are in EnvExtraConfig type:

      const Config = loadConfig({
        ENV: { type:'string' },
        // with "ENV" env == "prod"
      }, null, null, new EnvExtraConfig({ readonlyDefault: false }))
      Config.ENV = 'dev'; // after that "Config02.ENV" have the value "dev"
      • exitOnError: defaults to process.exit
        A functions to be called when some error occurs during load, like a parse error, an env not defined, a choices error.
        Define to null to not exit on errors.

      • exitErrorCode: defaults to 1
        Error code to use in the call of the functions defined in exitOnError.

      • throwOnError: defaults to false
        Instead of calling exitOnError, when this configurations is true then an Error will be thrown, so that it can be catch by your code.

      • loggerError: defaults to console.error
        Logger to call when errors occurs. Need to have similar interface of console.error.
        Set to null to not log errors.

      • readonlyDefault: defaults to true
        Default behavior of readonly item configuration.