Home > OS >  optinal function in interface gives Cannot invoke an object which is possibly 'undefined'
optinal function in interface gives Cannot invoke an object which is possibly 'undefined'

Time:02-08

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

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

CodePudding user response:

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

  •  Tags:  
  • Related