Home > Mobile >  condition to check if variable is defined (typescript)
condition to check if variable is defined (typescript)

Time:01-05

What is the best way to check if the variable has a value or not, in typescript 4.2? My variable could take a boolean value. I guess if(v){} won't work, since false could ignore the condition.

CodePudding user response:

In your case the variable can take a boolean value, so you need to check the type of your variable

if( typeof v === 'boolean'){ // enters code block if variable v is boolean and have a value }

or you can simply check if the type of a variable is not undefined

if( typeof v !== 'undefined'){ //enters code block if not undefined }
  •  Tags:  
  • Related