【问题标题】:Cast process.env to <any> with TS使用 TS 将 process.env 转换为 <any>
【发布时间】:2018-12-02 23:39:07
【问题描述】:

我有几个这样的日志语句:

log.info('docker.r2g run routine is waiting for exit signal from the user. The container id is:', chalk.bold(process.env.r2g_container_id));
log.info('to inspect the container, use:', chalk.bold(`docker exec -it ${process.env.r2g_container_id} /bin/bash`));
log.info('to stop/kill the container, use kill, not stop:', chalk.bold(`docker kill ${process.env.r2g_container_id}`));

当我使用 tsc 进行转换时,我收到以下错误:

src/commands/run/run.ts(132,94): error TS2339: Property 'r2g_container_id' does not exist on type 'ProcessEnv'.

133 log.info('to stop/kill the container, use kill, not stop:', chalk.bold(`docker kill ${process.env.r2g_container_id}`));

process.env 转换为any 或诸如此类的最佳方法是什么,以消除这些错误?或者也许我可以扩展 ProcessEnv 以包含我正在寻找的环境变量?不过前者似乎还不错。

我试过了:

declare global {

  namespace NodeJS {
    export interface ProcessEnv {
      r2g_container_id: string,
      docker_r2g_is_debug: string
    }
  }

}

但这不太对。

这是一个类似的问题,我们可以参考:using process.env in TypeScript

【问题讨论】:

标签: node.js typescript typescript2.0 tsc


【解决方案1】:
(<any>process.env).r2g_container_id

这应该足以转换为类型any

【讨论】:

  • 如果您不想在文件中的多个位置投射它,我相信您也可以为其添加别名,例如const env = &lt;any&gt;process.env
  • 赞成,但不是我真正想要的 tbh,因为这是我不想做的很多手动调用。
【解决方案2】:

这似乎有效:

declare global {

  namespace NodeJS {

    export interface ProcessEnv  {
      [key:string]: string,
      r2g_container_id: string,
      docker_r2g_is_debug: string,
      docker_r2g_fs_map: string
      HOME: string
    }

  }

}

我不确定这是否会增加或覆盖现有定义,但无论如何编译错误都消失了。

【讨论】:

    【解决方案3】:

    这似乎也有效:

    declare namespace NodeJS {
      export interface EnvironmentVariables {
        r2g_container_id: string,
        docker_r2g_is_debug: string
      }
    }
    

    在这里找到: https://github.com/typings/registry/issues/770

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-03
      相关资源
      最近更新 更多