Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Typescript how do you type for (const element of elements ) {}

Tags:

typescript

I tried

for (const element as ElementType of elements ) {}

or

for (const element of elements as ElementType) {}

Both are incorrect.

like image 439
user310291 Avatar asked Sep 16 '25 06:09

user310291


2 Answers

You dont have to do anything.

interface TestElement {
    id: Number;
}

const arr: TestElement[] = [];

for (const element of arr ) {
    element // It is implicitly cast to TestElement
}
like image 150
mamichels Avatar answered Sep 18 '25 08:09

mamichels


I'm not sure why Typescript doesn't allow type annotations or type assertions on variables like this in for/of loops. You can achieve something similar by asserting the type of the array, rather than the element:

let arr: any = [1, 2, 3, 4];

for (let x of (arr as number[])) {
    x // number
}

It's a bit messy because of the extra brackets, but it does the job.

Playground Link

like image 23
kaya3 Avatar answered Sep 18 '25 09:09

kaya3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!