我该如何修复该错误The left-hand side of a 'for...in' statement cannot use a type annotation.?未编译的相关代码是一个简单的 for...in 循环:
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)
}
Run Code Online (Sandbox Code Playgroud)
我知道不可能输入常量role,但如果我不这样做,则const isRole = roles.includes(roles)不会有效:Argument of type 'string' is not assignable to parameter of type '"a" | "b" | "c"'.
Pau*_*a T 23
我可能是错的,因为我只使用循环完成此操作of,但您应该能够在集合(右侧)上强制执行类型定义,该定义通知项目上的类型。
例如:
for (role in roles as Roles[])
Run Code Online (Sandbox Code Playgroud)
这应该使每个元素的类型为Roles.
小智 5
您可以在同一范围内声明 let 变量并设置变量的类型。您的示例如下。
const 角色 = ['a', 'b', 'c'] as const
type Roles = typeof Roles[number] // 'a' | 'b' | 'C'
常量角色 = {
'A': '...',
'b': '...',
'C': '...',
}
让角色:角色;
for(角色中的角色){
const isRole = 角色.includes(角色)
}