-1

I wonder how can I solve this without setting strictNullchecks to false.

if (someArray.find(element => element.id === x.id) {
    return someArray.find(element => element.id === x.id).message
}

or

const x = someArray.find(element => element.id === x.id) ? someArray.find(element => element.id === x.id).message : "No message"

As you know, TypeScript shows an error like "Object is possibly undefined" when I set the strictNullChecks to true.

Is it the best choice to set the strictNullChecks to false?

------- added contents -------

screen capture

if (self.cases.find(element => element.code === self.statusCode)) {

                // NOTE: do not use 'case' to variable instead of the 'selectedCase'
                const selectedCase = self.cases.find(element => element.code === self.statusCode)
                console.log(selectedCase.message)
                return (
                    self.statusCode + " " + selectedCase.message
                )
            } 

Q1. When I try to use 'case' as variable. It requires variable declaration. is it pre-declared words?

Q2. the console.log(selectedCase.message) and selectedCase.message occur the error Object is possibly undefined also.

Why this happens..?

Noah
  • 3
  • 2
  • 1
    Just extract `someArray.find(element => element.id === x.id)` to a variable, that way you don't have to run the loop twice anyway. – jonrsharpe Feb 01 '20 at 08:43
  • But both your examples seem to work in the playground anyway: http://www.typescriptlang.org/play/index.html#code/GYVwdgxgLglg9mABMOcAUBnOBbApgQQCdCBDATwC5ESwyBtAXQBpEAPKmsgSioykJhgA5ogDeAKERTEMYIkw4CxcgDpgggCZpcAG1x4wURAF4AfIl37chlTA0njxtrY1cuYydK+FcUEISQsPCJSMjVNbT0DIzMLKOsoFwcnVhcuFTwMDBIhXABuTykAX0LEHz8AxAAiADk4REzs3KqCkvFQSFgERAAjEkIFYOVKalpGFnZR7l5+QREJb19-QMUQ1XUwLUtok3NthKTHFLTSrwB+RCClUPDNyKtDXbiHxLtk5zt0xpzcU+kqWr1b7NVridrgaDwJB9ABeg2u5A4Y2YbCR00us2EHi8EAQfDiJkuq2Gty28UesX2NjeRw+rgKiwqSF0iAuugyuCyP0QALqDU5TVwLXEJSAA – jonrsharpe Feb 01 '20 at 08:45
  • `someArray.find(element => element.id === x.id)?.message`? – VLAZ Feb 01 '20 at 09:03
  • VLAZ, your comment is working. Thank you! (But I got some additional questions... ) – Noah Feb 01 '20 at 09:54

1 Answers1

0

Rather than searching the array twice, you should store the result in a temporary variable, and then check if that is defined.

Eg:

const foundElement = someArray.find(...)

if (foundElement) {
  console.log(foundElement.message)
}
Michael
  • 2,189
  • 16
  • 23