Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

TS2345: Argument of type 'number | undefined' is not assignable to parameter of type 'number'

Ask Question

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.

.id is possibly undefined. Use a non-null assertion like tabs[0].id! or better yet, check in your code to make sure it isn't undefined. – Aaron Beall Oct 16, 2018 at 15:08

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!

Or write code to ensure that id is not null:

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

I'm guessing, but maybe typescript thinks that your tabs array could be empty (and thus not have an item at index [0]) - which is why it's type is inferred as number or undefined?

If this is the case, you should check that tabs[0] exists before trying to access the id property on it.

Even I think Its a problem with typescripts inference, because i found the solution just now. :) – Shobi Oct 16, 2018 at 15:04

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.