Skip to main content

@baeta/env

Interfaces

EnvOptions<T, R, D>

Type Parameters

Type Parameter

T extends EnvTypes

R extends boolean | undefined

D extends EnvInferType<T> | undefined

Properties

PropertyTypeDescription

type

T

The expected type of the environment variable.

default?

D

Default value if the environment variable is not provided.

required?

R

Whether the environment variable is required.

resolver?

(value: string) => EnvInferType<T>

Custom resolver to convert the environment variable to the expected type.

Type Aliases

EnvInferType<T>

EnvInferType<T>: T extends "string" ? string : T extends "number" ? number : boolean

Maps environment variable types to their TypeScript equivalents.

Type Parameters

Type ParameterDescription

T extends EnvTypes

The environment variable type


EnvTypes

EnvTypes: "string" | "number" | "boolean"

Supported environment variable types.

Functions

createEnvParser()

createEnvParser(getValue): <T, R, D>(key, options) => R extends true ? EnvInferType<T> : D extends undefined ? undefined | EnvInferType<T> : EnvInferType<T>

Creates an environment variable parser.. See https://baeta.io/docs/guides/environment

Parameters

ParameterTypeDescription

getValue

(key) => undefined | string

Function to retrieve environment variable values

Returns

Function

A parsing function that converts environment variables to strongly-typed values

Type Parameters
Type Parameter

T extends EnvTypes

R extends undefined | boolean

D extends undefined | string | number | boolean

Parameters
ParameterType

key

string

options

EnvOptions<T, R, D>

Returns

R extends true ? EnvInferType<T> : D extends undefined ? undefined | EnvInferType<T> : EnvInferType<T>

Example

const parse = createEnvParser((key) => process.env[key]);

const port = parse("PORT", {
type: "number",
required: true,
default: 3000,
});

const debug = parse("DEBUG", {
type: "boolean",
default: false,
});

Throws

When:

  • A required value is missing and has no default
  • The value type doesn't match the specified type
  • A custom resolver returns an incorrect type