Typescript selection box object might possibly be undefined

Issue

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:

 <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"

Answered By – Kenny

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.