node.js - 基于 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)
解决方案
只需使隐式any
显式:
const envConfig: any = (config as any)[environment];
当您尝试通过['propertyName']
而不是访问对象的属性时,通常会出现此错误.propertyName
,因为这种形式在许多情况下会绕过 TypeScript 的类型检查。
推荐阅读
- javascript - 即使在将事件绑定到页面文档 DOM 之后,jQuery 单击事件也无法正常工作
- postgresql - 在 PostgreSQL 中两次加入同一个表的最佳方法是什么?
- python-3.x - pandas.series.split(' ',expand =True) 带列名
- kubernetes - 如何将主机路径与入口中的服务路径映射?
- python - 如何防止在 MatlabR2018b 中加载后保存的 Python .mat 文件的像素值减少或丢失?
- php - setlocale() 函数返回 false
- javascript - npm 错误!尝试安装 express 时出现代码 EAI_AGAIN 错误
- ios - GradientLayer 在 iOS Swift App 中移动到左上角
- javascript - 是否可以选择离子切换更改变量值及其属性
- javascript - jQuery 函数无法使用 .load() 刷新 div 标签