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

optinal function in interface gives Cannot invoke an object which is possibly 'undefined' when inside a condition

I cannot removed an error even when I wrap it in a condition :

I have this in my interface :
enter image description here

and then in my code I do this :
enter image description here

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

I also have a condition to make sure this.customType exist

and that red line says :
Cannot invoke an object which is possibly ‘undefined’.

How is this possible if I make sure it exist in a if right before?

I’ve made a typescript code here, apparently it’s because I’m using a variable. anyway around this?
https://www.typescriptlang.org/play?ts=3.9.7#code/KYDwDg9gTgLgBASwHY2FAZgQwMbDgYQFcBnGCAW3wiXQQHNi4BvAKDjgG0BrYATwC44pKMjoBdQa3bsAbpgA2CACaZUAfgAU6eZjqDMSXgEpBAIwgR5wAwG42cAL52HLFtmqk42EmUrVaDIJEpBRUNPSMALzMLBwA5KYGBsBxEjHScHKKKqgaxEbpGXBQwDCEUEhCdhkOADRsLi5uHvDeIeQAKrxgwPgAFhbEwJXRCUlIKa4sCOhwGm2+YQHE8YlIyakAdFnKqsAFUtILof4Rq+MpYtsKu7lx8pZxRs5T0+jzPhRdPf2Dw3AAMgBXk+fnCDAO9hmc2OYOWHFh316AwgQyQVx2OX2hQysKWZ0R3WRf3R12yew090ez3sjSAA

>Solution :

In your condition, try writing it as:

if (customConfigs?.[this.customType]?.validate) {

I’d suspect the error is on the possibility of either customConfigs or customConfigs[this.customType] of being undefined

EDIT

Thanks for the playground, that highlights where the issue stands; Forget the above and simply have it as customConfigs[this.customType].validate?()

The question mark before the validate function, allow you to invoke the function only if the object beforehand exists

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