导出的envKeys变量仅在checkEnv.ts中未定义的问题求助
问题:
envKeys在checkEnv.ts中显示未定义,但types.ts中正常定义 报错信息:
return botConfig_1.envKeys.reduce((acc, current) => { TypeError: Cannot read properties of undefined (reading 'reduce')
项目配置
- 编译目标:ES2022
- 模块规范:CommonJS
- 模块解析方式:Node
- 启用
useStrict
相关文件代码
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 };
已尝试的无效方法
- 检查循环依赖(未发现)
- 删除dist文件夹重新编译
- 将
envKeys移至checkEnv.ts内(此方法有效但不符合需求) - 检查编译后的文件(未发现异常)
解决方案
核心问题是循环依赖导致的运行时执行顺序错误:botConfig.ts先调用getEnvConfig()(依赖envKeys),但envKeys定义在文件末尾,此时还未初始化,所以checkEnv.ts拿到的是undefined。TypeScript类型导入是静态的,不会影响运行时,因此types.ts能正常使用envKeys。
方法1:拆分envKeys到独立模块
创建configs/envKeys.ts:
export const envKeys = ["TOKEN", "ID", "PREFIX", "MONGO_URI"] as const;
然后在三个文件中统一导入这个模块:
checkEnv.ts:import { envKeys } from "../configs/envKeys";botConfig.ts:import { envKeys } from "./envKeys";types.ts:import { envKeys } from "./envKeys";
彻底消除循环依赖,避免执行顺序问题。
方法2:调整botConfig.ts代码顺序
将envKeys的定义移到文件最顶部,确保调用getEnvConfig()前变量已初始化:
import { botConfigType } from "./types"; import { getEnvConfig, getSanitzedConfig } from "../utils/checkEnv"; // 先定义envKeys export const envKeys = ["TOKEN", "ID", "PREFIX", "MONGO_URI"] as const; // 再调用依赖函数 const { TOKEN, ID, PREFIX, MONGO_URI } = getSanitzedConfig(getEnvConfig()); const data: botConfigType = { token: TOKEN, ID: ID, prefix: PREFIX, owners: [""], mongo_uri: MONGO_URI, }; export default data;
内容的提问来源于stack exchange,提问作者Joniii11
相关产品推荐
相关产品推荐

