类型'string |的参数未定义”不能分配给“字符串”类型的参数

我的代码:

const configPath = process.env[`${configPrefix}_CONFIG_PATH`]
    ? path.resolve(process.env[`${configPrefix}_CONFIG_PATH`])
    : path.resolve('ab','config');

错误:

application/libs/config.ts:18:20 - error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
  Type 'undefined' is not assignable to type 'string'.

18     ? path.resolve(process.env[`${configPrefix}_CONFIG_PATH`])

为什么要抱怨?我正在检查process.env[`${configPrefix}_CONFIG_PATH`]上是否未定义,然后与?:决定取哪个值。

xw20090630 回答:类型'string |的参数未定义”不能分配给“字符串”类型的参数

我用以下代码解决了这个问题:

const configPath = process.env[`${configPrefix}_CONFIG_PATH`] || path.resolve('ab','config');

虽然我的第一个示例中的Typescript为什么不起作用,但没有回答。

,

在第一个示例中,如果存在process.env["${configPrefix}_CONFIG_PATH"],则返回path.resolve(process.env["${configPrefix}_CONFIG_PATH"]),但是将其包装在path.resolve()中显然仍然会导致undefined

const configPath = process.env[`${configPrefix}_CONFIG_PATH`]
    ? path.resolve(process.env[`${configPrefix}_CONFIG_PATH`])
    : path.resolve('ab','config');

在您自己的答案中,您返回与未定义检查相同的值,因此在这种情况下您就不会遇到问题。

本文链接:https://www.f2er.com/3166794.html

大家都在问