我的代码是:
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'.
我试过
const port: Number = parseInt(process.env.PORT, 10) || 3000;
但它给了我另一个错误:
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
我做错了什么?
答案 0 :(得分:2)
const port: Number = parseInt(<string>process.env.PORT, 10) || 3000
这解决了它。我认为它被称为Type Assertion
答案 1 :(得分:0)
这也应该有效。
const port: Number = parseInt(process.env.PORT as string, 10) || 3000