最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

基于环境的参考导入对象

IT培训 admin 6浏览 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的类型检查。

基于环境的参考导入对象

在我的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. 暂无评论