create-typed-env
Version:
Create a type-safe proxy for accessing environment variables
57 lines (55 loc) • 1.84 kB
TypeScript
/**
* Fallback value for missing environment variables.
* Supports string, object and environment-specific fallback values.
*/
type FallbackValue = string | Record<string, string> | ((key: string) => string);
/**
* Fallback values for environment variables per Node.js environment.
*/
type NodeEnvs<TValue> = {
development?: TValue;
test?: TValue;
production?: TValue;
};
/**
* Fallback value for missing environment variables.
* Supports string, object and environment-specific fallback values.
*/
type Fallback = FallbackValue | {
env: NodeEnvs<FallbackValue>;
};
type Log = boolean | NodeEnvs<boolean>;
/**
* Options for creating an environment variable proxy.
*/
type CreateEnvOptions<TLazy extends boolean> = {
/**
* The source of environment variables.
* Defaults to `process.env`.
*/
env?: NodeJS.ProcessEnv | Record<string, string>;
/**
* If true, the environment variable will be getter and setter functions.
* Otherwise, the environment variable will be a direct property.
*/
lazy?: TLazy;
/**
* Fallback value for missing environment variables.
*/
fallback?: Fallback;
/**
* If true, missing environment variables will be logged to the console.
*/
log?: Log;
};
type TypedEnv<TEnv extends Record<string, any>, TLazy extends boolean> = TLazy extends true ? {
-readonly [K in keyof TEnv]: (value?: string) => string;
} : {
-readonly [K in keyof TEnv]: string;
};
/**
* Creates a type-safe proxy for accessing environment variables.
*/
declare function createTypedEnv<TEnv extends Record<string, any>>(options?: CreateEnvOptions<false>): TypedEnv<TEnv, false>;
declare function createTypedEnv<TEnv extends Record<string, any>>(options: CreateEnvOptions<true>): TypedEnv<TEnv, true>;
export { createTypedEnv };