Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The left-hand side of a 'for...in' statement cannot use a type annotation

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"'.

like image 860
920smmsmsms Avatar asked Jul 23 '19 23:07

920smmsmsms


2 Answers

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

like image 88
Tomas Schaffer Avatar answered Nov 05 '22 03:11

Tomas Schaffer


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.

like image 32
Eugene Christian Avatar answered Nov 05 '22 03:11

Eugene Christian