Alexander Mills
Alexander Mills

Reputation: 100080

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

Upvotes: 1

Views: 735

Answers (3)

Matt Browne
Matt Browne

Reputation: 12419

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

Upvotes: 1

Alexander Mills
Alexander Mills

Reputation: 100080

This seemed to work:

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
    }

  }

}

I am not sure if that augments or overrides the existing definition, but in any case the compilation errors are gone.

Upvotes: 1

Armen Vardanyan
Armen Vardanyan

Reputation: 3315

(<any>process.env).r2g_container_id

This should be enough to cast to type any

Upvotes: 1

Related Questions