如何在TypeScript中读取节点环境变量?

如果我使用process.env。NODE_ENV我有这个错误:

Property 'NODE_ENV' does not exist on type 'ProcessEnv'

我已经安装了@types/node,但它没有帮助。


当前回答

您可以为此使用类型断言

Sometimes you’ll end up in a situation where you’ll know more about a value than TypeScript does. Usually this will happen when you know the type of some entity could be more specific than its current type. Type assertions are a way to tell the compiler “trust me, I know what I’m doing.” A type assertion is like a type cast in other languages, but performs no special checking or restructuring of data. It has no runtime impact, and is used purely by the compiler. TypeScript assumes that you, the programmer, have performed any special checks that you need.

例子

const nodeEnv: string = (process.env.NODE_ENV as string);
console.log(nodeEnv);

或者,您可能会发现像env-var这样的库更适合这个特定的目的——

在node.js中使用正确类型加载和清除环境变量的解决方案

其他回答

我知道这将帮助一些人搜索这个,不能找到简单的答案,为什么你的过程。Env变量让你的编译器抱怨:

安装@types /节点:

npm i @types/node

然后当你将env作为字符串包含时,这样做:

process.env.YOUR_ENV ?? ''

双问号允许您检查null/undefined。

重要提示:如果你有一个web应用程序,你正在使用webpack。定义流程。Env在你的窗户上,那么这些就是你要找的类型:

declare namespace process {
    let env: {
        // this is optional, if you want to allow also
        // other values than the ones listed below, they will have type 
        // string | undefined, which is the default
        [key: string]: string
        commit_hash: string
        build_time: string
        stage: string
        version: string
        // ... etc.
    }
}

还可以使用类型保护函数。像这样,返回类型是

parameterName is string

如。

function isEnvVarSpecified(envVar: string | undefined): envVar is string {
  if(envVar === undefined || envVar === null) {
    return false;
  }
  if(typeof envVar !== 'string'){
    return false;
  }
  return true;
}

然后你可以调用它作为类型保护:

function myFunc() {
  if(!isEnvVarSpecified(process.env.SOME_ENV_VAR')){
      throw new Error('process.env.SOME_ENV_VAR not found')
  }
  // From this point on the ts compiler won't complain about 
  // process.env.SOME_ENV_VAR being potentially undefined
}

使用节点进程的最佳和最简单的方法。你的typescript项目中的env是首先用tsc编译,然后用node提供你的env var运行编译后的javascript文件。ts是你想要的输出目录也是编译文件的名称,我使用dist作为输出目录和index.js为例):

cd my-typescriptproject
tsc
NODE_ENV=test node ./dist/index.js

下面是一个简短的函数,它保证会拉动进程。将Env值作为字符串—或以其他方式抛出错误。

对于更强大(但也更大)的东西,这里的其他人建议使用env-var。

/**
 * Returns value stored in environment variable with the given `name`.
 * Throws Error if no such variable or if variable undefined; thus ensuring type-safety.
 * @param name - name of variable to fetch from this process's environment.
 */
export function env(name: string): string {
  const value = process.env[name];

  if (!value) {
    throw new Error(`Missing: process.env['${name}'].`);
  }

  return value;
}

然后你应该能够编写如下代码:

let currentEnvironment: string;
currentEnvironment = env('NODE_ENV');