Vjerci
Vjerci

Reputation: 580

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.

Upvotes: 22

Views: 16276

Answers (2)

anthumchris
anthumchris

Reputation: 9072

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

const links: NodeListOf<HTMLElement> = document.querySelectorAll('a')
links.forEach(a => a.setAttribute('target', '_blank'))

Upvotes: 0

Rainmaker
Rainmaker

Reputation: 632

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);
}

Upvotes: 28

Related Questions