首页 新闻 会员 周边

typescript: 如果检查 string | undefined 类型的值是否为空

0
悬赏园豆:30 [已解决问题] 解决于 2023-10-06 21:01

比如下面的函数

export function showInputBox(options?: InputBoxOptions, token?: CancellationToken): Thenable<string | undefined>;

使用下面的代码检查值是否为空

const pat = await window.showInputBox(opt)
if (!pat) throw new Error('个人访问令牌(PAT)不能为空')

eslint 提示

Unexpected nullable string value in conditional. Please handle the nullish/empty cases explicitly.eslint@typescript-eslint/strict-boolean-expressions

请问如何解决?

dudu的主页 dudu | 高人七级 | 园豆:30943
提问于:2023-10-06 19:31
< >
分享
最佳答案
0

我没用过这个编程语言,搜了搜(虽然不太一样,但我觉得应该这个解决方案应该是正确的):

https://stackoverflow.com/questions/64940604/typescript-eslint-strict-boolean-expressions-check-for-falsy-value

根据我的推断,应该是对 pat 变量检查不严格导致的警告,请修改对空检查的方式。


You could try using the nullish coalescing operator (??) like this:

if (!(text ?? '')) {}

text ?? '' evaluates to '' if it is undefined and text otherwise.

This is equivalent to the following:

if (!(text !== null && text !== undefined ? text : '')) {}
收获园豆:30
寂静的羽夏 | 小虾三级 |园豆:1803 | 2023-10-06 19:42

if (!(pat ?? '')) 也无法通过 eslint 的检查

Unexpected string value in conditional. An explicit empty string check is required

但这样写之后,quick fix 生成了下面的修复代码

  if ((pat ?? '').length === 0) { }
dudu | 园豆:30943 (高人七级) | 2023-10-06 20:35

@dudu: 如果给出修复代码,过了检测就好,这检测主要是防止不规范的写法。因为我没用过 ts ,所以具体细节其实我也不清楚。不过最后再给你一个参考,dudu 您应该比我更懂一些,里面写了一些详细说明,希望对您有帮助:https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/strict-boolean-expressions.md

寂静的羽夏 | 园豆:1803 (小虾三级) | 2023-10-06 20:45
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册