typescriptstrictnullchecks

Can I solve this one without strictNullChecks: false?


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..?


Solution

  • 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)
    }