Reputation: 25
I know there are a lot of questions about 'Object is possibly undefined' errors in typescript, but I have not found an answer to my particular question. I have an array with items and I want to access an element by index. I can put checks for each part of the element I want to access in an if statement around it, but it will still tell me that it is possibly undefined.
My code looks like this:
if(this.classLevels && this.classLevels[finalLevel] && this.classLevels[finalLevel].class){
this.classLevels[finalLevel].class.currentLevel += 1;
}
class
seems to be what can be undefined. It automatically wants to put a questionmark there, like this.classLevels[finalLevel].class?.currentLevel += 1;
, but in that case I get the error that The left-hand side of an assignment expression may not be an optional property access
.
I don't really want to disable the strict undefined check, but if I cannot get it to work with elements in an array, I may have to. Is there something I am missing here?
Upvotes: 0
Views: 6398
Reputation: 120400
Assuming that you have noUncheckedIndexedAccess
enabled, your best bet would be to make an intermediate variable:
const finalLevelClass = this.classLevels?.[finalLevel]?.class;
if (finalLevelClass) {
finalLevelClass.currentLevel += 1;
}
Upvotes: 3