最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

基于环境的参考导入对象

运维笔记admin10浏览0评论

基于环境的参考导入对象

基于环境的参考导入对象

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

config.ts

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的类型检查。

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论