BD One

BD One

  • NA
  • 11
  • 573

how to put a declaration in a if-function?

Feb 23 2021 6:27 PM
hey community, 
 
I am making a pdf with information from a website. My problem is the image. If there is an image it works with the codes:
  1. const first_picture_url: string = product.pictures[0].url;  
  2. const other_picture_urls: string[] = product.pictures.filter(  
  3.               
  4. (_: { url }, index: number) => index > 0).map((picture: { url }) => picture.url);  
If there is no image, i get the Error 

TypeError: Cannot read property 'url' of undefined.

 
 i found out i could prevent this with
  1. if(product.pictures.length<1)  
 but if i try to put the first codes in this if-function it doesnt work.
 
My try:
  1. if(product.pictures.length>0){  
  2.       const first_picture_url: string = product.pictures[0].url;  
  3.       const other_picture_urls: string[] = product.pictures.filter(  
  4.               
  5.        (_: { url }, index: number) => index > 0).map((picture: { url }) => picture.url);  
  6. }  
  7.  else  
  8. {      
  9.       const first_picture_url: string = String(product.airCoolingIntegrated);  
  10. }  
it doesnt work, i get the message  "first_picture_url" is declared but its value is never read"
 
i just want these lines not be initiated if the length of the attribute is 0. (so no picture existing).
 
Can anyone help me with that maybe?
 
Greetings 

Answers (3)