I am trying to create a chrome extension in typescript.
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'.
I tried converting the id to an integer using parseInt(), but still its not preventing the error.
答案 0 :(得分:1)
我正在猜测,但也许打字稿认为您的tabs数组可能为空(因此索引[0]处没有项目)-这就是为什么将其类型推断为数字或未定义的原因?
在这种情况下,您应先检查tabs [0]是否存在,然后再尝试访问其上的id属性。
答案 1 :(得分:1)
Chrome的标签.id
可能未定义(因为它是defined as optional in the type definitions),这意味着在使用strictNullChecks
时,您必须使用非null断言:
tabs[0].id!
或编写代码以确保id不为空:
if (tabs[0].id) { // send message