有条件地扩展接口

Extending an interface conditionally

提问人:CreativeDifference 提问时间:10/20/2023 最后编辑:CreativeDifference 更新时间:10/20/2023 访问量:35

问:

export async function checkEnv(envPath: string): Promise<void> {
    if(await (Bun.file(envPath)).exists() === false) {
        logger.error("Cannot access .env configuration file, creating a new one with default configuration...");
        let defaultJWTSecret = randomBytes(512).toString("hex");
        await Bun.write(envPath, `# The string, with which all of the JSONWebTokens are encrypted\n# Defaults to 512 random bytes if left blank\n# WARNING: IF YOU CHANGE THE JWTSECRET, THE ENTIRE DATABASE WILL BE INVALIDATED, THIS WILL LEAD TO UNEXPECTED BEHAVIOUR\n# IN THAT CASE PLEASE USE THE -d FLAG TO CLEAR THE DATABASE\nJWTSECRET=${defaultJWTSecret}\n# Set this to valid Port (1-65535)\nPORT=9495`);
        process.env.PORT = "9495";
        process.env.JWTSECRET = defaultJWTSecret;
        logger.info("Done!");
    }

    const parsedEnv = envSchema.safeParse(Bun.env);
    
    //@ts-ignore Opened issue at https://github.com/colinhacks/zod/issues/2883
    if(parsedEnv.success === false) {
        JSON.parse(parsedEnv.error.message).forEach((errorMessage: string) => {
            logger.error(errorMessage);
            process.exit(1); 
        });
    }
    console.log(parsedEnv);
}

但是,这会抛出“类型'字符串'不可分配给类型'数字'”,因为我像这样扩展了 Node.js process.env 类型:


declare global {
    namespace NodeJS {
        interface ProcessEnv extends z.infer<typeof envSchema> {}
    }
}

我无法覆盖“PORT”,因为在我的 zod 模式中,“PORT”是一个带有字符串的数字(从字符串解析而来),因为我刚刚用 .env 解析的结果扩展了它。 在我完成解析后,有什么方法可以扩展process.env吗?

TypeScript 命名空间扩展

评论


答: 暂无答案