Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast declaration variable inside for of loop

Is there a shorter and simplified version of casting a declaration variable inside of "for of" loop.

let array1: Array<String | Number>;
for (let a of array1) {
    let ab: String = <String>a;
}

I am aware casting the whole array would work, but tbh i would feel much more happy if i could either cast or set the datatype of declaration variable "a" instead of casting the whole array, Is something like that possible? if i type let <String>a or let a:String it doesn't work.

like image 357
Vjerci Avatar asked May 28 '17 04:05

Vjerci


2 Answers

ref TypeScript casting arrays

let array1 : Array<string | number> = [];
array1.push('abc', 9, 'def', 10);
for (let a of  array1 as Array<string> ){
  console.log(a);
}
like image 190
Rainmaker Avatar answered Nov 16 '22 02:11

Rainmaker


Similarly, forEach iterations on DOM NodeList would be cast like:

const links: NodeListOf<HTMLElement> = document.querySelectorAll('a')
links.forEach(a => a.setAttribute('target', '_blank'))
like image 31
AnthumChris Avatar answered Nov 16 '22 02:11

AnthumChris