TS2345:类型“number |”的参数未定义' 不可分配给'number' 类型的参数

2024-04-22

我正在尝试在打字稿中创建一个 chrome 扩展。

我有以下代码,我尝试从后台脚本向 contentscript 发送消息。

// background script 
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
   chrome.tabs.sendMessage(tabs[0].id, {action: "open_dialog_box"}, function(response) {
      console.log(response);
   });  
});

但打字稿给出以下错误

ERROR in /Users/shobi/Projects/Chrome Extensions/src/js/background.ts(8,37)
      TS2345: Argument of type 'number | undefined' is not assignable to parameter of type 'number'.
  Type 'undefined' is not assignable to type 'number'.

我尝试使用 parseInt() 将 id 转换为整数,但仍然无法防止错误。


Chrome 的标签.id可能是未定义的(因为它是在类型定义中定义为可选 https://github.com/DefinitelyTyped/DefinitelyTyped/blob/7d616512eb210a0d1843adcfcce63a5c1fd734ba/types/chrome/index.d.ts#L5981),这意味着当使用strictNullChecks您必须使用非空断言:

tabs[0].id!

或者编写代码以确保 id 不为 null:

if (tabs[0].id) { // send message
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

TS2345:类型“number |”的参数未定义' 不可分配给'number' 类型的参数 的相关文章

随机推荐