Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript selection box object might possibly be undefined

I have a selection box and an array of tabs. I’m getting an error that it might be possibly undefined.

here are the tabs ( might be mutable in future) :

const tabs = [
  { name: "1 tab",  current: true },
  { name: "2 tab",  current: false },
  { name: "3 tab",  current: false },
];

here is the selection part:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 <label htmlFor="question-tabs" className="sr-only">
        Select a tab
      </label>
      <select
        id="question-tabs"
        className="block w-full"
        defaultValue={tabs.find((tab) => tab.current).name}
      >
        {tabs.map((tab) => (
          <option key={tab.name}>{tab.name}</option>
        ))}
      </select>

I’m having some issue with this line:

defaultValue={tabs.find((tab) => tab.current).name

the error says that the object might be possibly undefined.
How can I check to see if it is undefined, and if so just put some default text?

I’ve tried something like this but it didn’t work:

defaultValue={tabs ? tabs.find((tab) => tab.current).name : ''}

>Solution :

find returns undefined if tabs doesn’t contain tab.
Using Optional Chaining (?.) and the Nullish Coalescing Operator (??), you can return a default value like so:

tabs.find((tab) => tab.current)?.name ?? "default"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading