I tried
for (const element as ElementType of elements ) {}
or
for (const element of elements as ElementType) {}
Both are incorrect.
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
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With