未使用 Typescript 分配环境变量

Sha*_*oon 14 typescript

我的代码是:

const port: Number = process.env.PORT || 3000;

[ts]
Type 'string | 3000' is not assignable to type 'Number'.
  Type 'string' is not assignable to type 'Number'.
Run Code Online (Sandbox Code Playgroud)

我试过

const port: Number = parseInt(process.env.PORT, 10) || 3000;
Run Code Online (Sandbox Code Playgroud)

但它给了我另一个错误:

Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
  Type 'undefined' is not assignable to type 'string'.
(property) NodeJS.Process.env: NodeJS.ProcessEnv
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Sha*_*oon 25

const port: Number = parseInt(<string>process.env.PORT, 10) || 3000
Run Code Online (Sandbox Code Playgroud)

这解决了它。我认为它被称为类型断言

  • 您还可以执行以下操作: `const port: Number = parseInt(\`${process.env.PORT}\`, 10) || 3000` 这将确保将字符串传递给 parseInt。 (10认同)
  • 我认为这不正确?`process.env.PORT` 可以是字符串,也可以是未定义的。您断言它不能在这里未定义,这是错误的。正如上面的评论答案所说,您应该使用 `parseInt(process.env.PORT || '3000')` 来覆盖未定义 `process.env.PORT` 的情况。 (6认同)