Issue
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
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);
Answered By - Phil
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.