TS2345:“数字|数字"类型的参数未定义"不能分配给“数字"类型的参数 [英] TS2345: Argument of type 'number | undefined' is not assignable to parameter of type 'number'

查看:716
本文介绍了TS2345:“数字|数字"类型的参数未定义"不能分配给“数字"类型的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在打字稿中创建chrome扩展名.

I am trying to create a chrome extension in typescript.

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

I have the following code, where I try to send a message to contentscript from the background script.

// 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);
   });  
});

但是打字稿出现以下错误

but typescript is giving the following error

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转换为整数,但是仍然不能防止错误发生.

I tried converting the id to an integer using parseInt(), but still its not preventing the error.

推荐答案

Chrome的标签.id可能未定义(因为它是

Chrome's tab .id is possibly undefined (because it's defined as optional in the type definitions), which means when using strictNullChecks you have to either use a non-null assertion:

tabs[0].id!

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

Or write code to ensure that id is not null:

if (tabs[0].id) { // send message

这篇关于TS2345:“数字|数字"类型的参数未定义"不能分配给“数字"类型的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆