在 TypeScript 中使用 process.env [英] using process.env in TypeScript

查看:319
本文介绍了在 TypeScript 中使用 process.env的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I read node environment variables in TypeScript?

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

If i use process.env.NODE_ENV I have this error :

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

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

I have installed @types/node but it didn't help.

推荐答案

无法保证在 Node 进程中哪些(如果有)环境变量可用 - NODE_ENV 变量只是一种由 Express 推广的约定,而不是 Node 本身内置的东西.因此,将它包含在类型定义中实际上没有意义.相反,他们定义了process.env 像这样:

There's no guarantee of what (if any) environment variables are going to be available in a Node process - the NODE_ENV variable is just a convention that was popularised by Express, rather than something built in to Node itself. As such, it wouldn't really make sense for it to be included in the type definitions. Instead, they define process.env like this:

export interface ProcessEnv {
    [key: string]: string | undefined
}

这意味着可以使用字符串索引 process.env 以获取字符串(或 undefined,如果未设置变量).要修复您的错误,您必须使用索引语法:

Which means that process.env can be indexed with a string in order to get a string back (or undefined, if the variable isn't set). To fix your error, you'll have to use the index syntax:

let env = process.env["NODE_ENV"];

或者,正如 jcalz 在评论中指出的那样,如果您使用的是 TypeScript 2.2 或更高版本,您可以使用点语法访问上面定义的可索引类型 - 在这种情况下,您的代码应该按原样工作.

Alternatively, as jcalz pointed out in the comments, if you're using TypeScript 2.2 or newer, you can access indexable types like the one defined above using the dot syntax - in which case, your code should just work as is.

这篇关于在 TypeScript 中使用 process.env的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆