Why does my exported const variable is only in 1 file undefined and in the other one is defined

Advertisements

First of all, hello!

The variable envKeys is undefined in the checkEnv.ts file. But in the file types.ts it is defined.
It is the first time, that something like this happened.

Here is the error:

return botConfig_1.envKeys.reduce((acc, current) => {

TypeError: Cannot read properties of undefined (reading 'reduce')

I use ES2022 as a target with commonjs, model resoulation is node and useStrict, if somebody is interested in that.

In advance, thank you for everyone who is willing to help me out in that situation.

checkEnv.ts

import { ENV, Config } from "../configs/types";
import { envKeys } from "../configs/botConfig";
import { config } from "dotenv";
config();

//const envKeys = ["TOKEN", "ID", "PREFIX", "MONGO_URI"] as const;

/**
 * This function gets the env and returns the specific things
 * @returns 
 */
export function getEnvConfig(): ENV {

    return envKeys.reduce((acc, current) => {
        acc[current] = process.env[current]
        return acc
    }, {} as ENV)
};
/**
 * This function returns every .env type that was specified. It gives it a proper Type and so much more.
 * @param config   The config that should check it trough
 * @returns 
 */
export function getSanitzedConfig(config: ENV): Config {
    for (const [key, value] of Object.entries(config)) {
        if (value === undefined) {
            throw new Error(`Missing key ${key} in .env`)
        }
    };
    
    return config as Config;
};

botConfig.ts

import { botConfigType } from "./types";
import { getEnvConfig, getSanitzedConfig } from "../utils/checkEnv";

const { TOKEN, ID, PREFIX, MONGO_URI } = getSanitzedConfig(getEnvConfig());

const data: botConfigType = {
    token: TOKEN,
    ID: ID,
    prefix: PREFIX,
    owners: [""],
    mongo_uri: MONGO_URI,

};

// Export the envKeys for the checkEnv file
export const envKeys = ["TOKEN", "ID", "PREFIX", "MONGO_URI"] as const;

// Export the botConfig
export default data;

types.ts

import { envKeys } from "./botConfig";

export type botConfigType = {
    token: string;
    ID: string;
    prefix: string;
    owners: string[];
    mongo_uri: string;
};

export type EnvKeys = typeof envKeys[number];
export type ENV = { [key in EnvKeys]?: string | undefined };
export type Config = { [key in EnvKeys]: string };

I already tried:

  • Checking for circual dependencys (did not find any)
  • Deleted the dist folder to update the code after compiling
  • Moving the const variable in the file (works then)
  • Checked the compiled file for any weird things in there (nothing found)

>Solution :

Might be a hoisting problem that occurs due to envKeys being used in botConfig.ts before it has been instantiated.

Try moving export const envKeys = ["TOKEN", "ID", "PREFIX", "MONGO_URI"] as const to the top of botConfig.ts (~ line 3), that might help.

Leave a ReplyCancel reply