Search code examples
node.jstypescripttypescript2.0tsc

Cast process.env to <any> with TS


I have a couple logging statements like so:

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}`));

when I transpile this with tsc, I get these errors:

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}`));

what is the best way to cast process.env to any or whatnot, to get rid of these errors? Or perhaps I can extend ProcessEnv to include the env variables I am looking for? The former seems fine though.

I tried this:

declare global {

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

}

but that's not quite right.

Here is a similar question we might defer to: using process.env in TypeScript


Solution

  • This seems to work too:

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

    Found here: https://github.com/typings/registry/issues/770