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

Check if nullable string property contains anther string with indexOf or includes gives expression expected error

I want to assign a value to a const conditionally and need to check if one nullable string property in my object contains another one. Based on this i will assign it the value of functionA or functionB. I have tried to use both ‘indexOf’ and ‘includes’ but typescript gives ‘Object is possibly undefined’ or ‘expression expected’. If you hav an idea on how to write this in a way which checks the nullable object and property and evaluate this please let me know, your help is appreciated!

using indexOf gives an error in Typescript Object is possibly ‘undefined’

const value = (req.object?.propertyA?.indexOf(req.object?.propertyB?) >= 0) ? 
    functionA(req.object?.propertyA?) :
    functionB(req.object?.propertyB?)

Using includes to check for the substring shows an error in Typescript with expression expected

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

const value = req.object?.propertyA?.includes(req.object?.propertyB?)  ? 
   functionA(req.object?.propertyA?) :
   functionB(req.object?.propertyB?)

>Solution :

The problem comes from req.object?.propertyB.

Both String.prototype.indexOf() and String.prototype.includes() expect a string parameter but your expression can potentially return undefined.

The ? suffix also doesn’t make sense.

I would alter your expression to be clearer and check for propertyB first…

const value =
  req.object?.propertyB && req.object?.propertyA?.includes(req.object.propertyB)
    ? functionA(req.object?.propertyA)
    : functionB(req.object?.propertyB);
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