![](/img/trans.png)
[英]Using bracket notation with a variable to access object property returns undefined
[英]Node Typescript: JSON undefined when using bracket notation
我有一个带有 typescript 的节点项目,我正在尝试从 json ZA8CFDE6331BD59EB26ACZF96 读取正确的 url。 但是,当使用方括号表示法时,我得到未定义。
{
"env":"dev",
"dev":{
"url": "url1"
},
"aws":{
"url": "url2"
}
}
由于某种原因,这不起作用:
const url = config[config.env].url;
下面的代码完成了我所需要的,但它不像上面那样灵活,我想了解为什么它不能以其他方式工作。
const cenv:string = config.env;
let url=null;
if( cenv === "dev")
url = config["dev"].url;
else
url = config["aws"].url;
这是我的 tsconfig 文件:
{
"compilerOptions": {
"lib": [
"es2017"
],
"moduleResolution": "node",
"noUnusedLocals": true,
"noUnusedParameters": true,
"sourceMap": true,
"target": "es2017",
"outDir": "lib",
"resolveJsonModule": true
},
"exclude": [
"node_modules"
]
}
json 被导入到项目中,如下所示:
import * as config from './config.json';
我建议创建config
文件夹
config/
settings.dev.json
settings.prod.json
index.js
// index.js
module.exports = function(){
switch(process.env.NODE_ENV){
case 'development':
return require('./settings.dev.json');
case 'production':
return require('./settings.prod.json');
default:
return {error or other settings};
}
};
如果你想使用方法,你可以这样做:
enum Enivornment {
Dev = "dev",
Aws = "aws"
}
type Config = {
"env": Enivornment,
} & {
[key in Enivornment]: ConfigItem
}
// this will help you have all environments in sync
type ConfigItem = {
"url": string
}
const config: Config = {
"env": Enivornment.Dev,
[Enivornment.Dev]: {
"url": "url1"
},
[Enivornment.Aws]:{
"url": "url2"
}
}
你可以在这里测试它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.