首页 > 解决方案 > 基于 env 引用导入的对象

问题描述

在我的 TypeScript Node 应用程序中,我希望引用与我的 NODE_ENV 变量匹配的导出对象。

配置文件

const test: { [index: string]: any } = {
    param1: "x",
    param2: {
        name: "John"
    }
}
const dev: { [index: string]: any } = {
    param1: "y",
    param2: {
        name: "Mary"
    }
}
export { test, dev }

main.ts

const environment = process.env.NODE_ENV || "development";
import * as config from "./config.ts";
const envConfig = config[environment]; //gives error Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'typeof import("/path_to_config.ts")'.ts(7053)

标签: node.jstypescript

解决方案


只需使隐式any显式:

const envConfig: any = (config as any)[environment];

当您尝试通过['propertyName']而不是访问对象的属性时,通常会出现此错误.propertyName,因为这种形式在许多情况下会绕过 TypeScript 的类型检查。


推荐阅读