使用 TS 将 process.env 转换为 <any>

Cast process.env to <any> with TS

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

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
    }
  }

}

但这不太正确。

这是一个类似的问题,我们可能会推迟:

(<any>process.env).r2g_container_id

这应该足以转换为类型 any

这似乎有效:

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
    }

  }

}

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

这似乎也有效:

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

在此处找到: https://github.com/typings/registry/issues/770