How can I fix the error The left-hand side of a 'for...in' statement cannot use a type annotation.
? The code in question that is not compiling is a simple for...in loop:
const roles = ['a', 'b', 'c'] as const
type Roles = typeof roles[number] // 'a' | 'b' | 'c'
const roles = {
'a': '...',
'b': '...',
'c': '...',
}
for (const role: Roles in roles) {
const isRole = roles.includes(roles)
}
I understand that is not possible to type the role
constant, but if I don't do it the const isRole = roles.includes(roles)
is not going to be valid: Argument of type 'string' is not assignable to parameter of type '"a" | "b" | "c"'.
You can declare let variable in same scope and set also type of variable. Your example is below.
const roles = ['a', 'b', 'c'] as const type Roles = typeof roles[number] // 'a' | 'b' | 'c' const roles = { 'a': '...', 'b': '...', 'c': '...', } let role: Roles; for (role in roles) { const isRole = roles.includes(roles) }
TSLint had similar issue in 2015. And solved it by disallowing type definitions inside of for loop as commented in the fix of issue.
So we are forbidden to place a type definition there.
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