0

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?

1 Answer 1

3

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works, thank you. I didn't know this was comming from a different typescript flag than the other error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.