Home > Mobile >  How can I declare an array outside a function in typescript?
How can I declare an array outside a function in typescript?

Time:04-13

I am creating an array of items with my drag and drop function:

drag.ondrop = (event: DragEvent) => {

   const items = [];

   while (length--) {
      items.push(event.dataTransfer.files[i].path);
      i  
    }

   console.log(items); 

}

But now everytime I drop a new element a new array is created. But I need the new item added to the array that already exists.

To achieve this I try to declare the array outside the function like this:

const items = [];

    drag.ondrop = (event: DragEvent) => {
    
       
    
       while (length--) {
          items.push(event.dataTransfer.files[i].path);
          i  
        }
    
    
    }

console.log(items); 

But I get an error:

TS7005: Variable 'items' implicitly has an 'any[]' type.

CodePudding user response:

Give it a type:

const items: string[] = [];

drag.ondrop = (event: DragEvent) => {  
  while (length--) {
    items.push(event.dataTransfer.files[i].path);
    i  
  }
}

console.log(items); 
  • Related