【问题标题】:The left-hand side of a 'for...in' statement cannot use a type annotation'for...in' 语句的左侧不能使用类型注释
【发布时间】:2019-12-02 01:08:36
【问题描述】:

如何修复错误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)
}

我知道无法输入 role 常量,但如果我不这样做,const isRole = roles.includes(roles) 将无效:Argument of type 'string' is not assignable to parameter of type '"a" | "b" | "c"'.

【问题讨论】:

  • 这是guess,如果我了解您的问题,请告诉我

标签: typescript types


【解决方案1】:

您可以在同一范围内声明 let 变量并设置变量的类型。您的示例如下。

const 角色 = ['a', 'b', 'c'] 作为 const type Roles = typeof roles[number] // 'a' | 'b' | 'C' 常量角色 = { '一种': '...', 'b': '...', 'C': '...', } 让角色:角色; for(角色中的角色){ const isRole = roles.includes(roles) }

【讨论】:

    【解决方案2】:

    TSLint 在 2015 年拥有 similar issue。并通过在 the fix of issue 中的注释中禁止 for 循环内的类型定义来解决它。

    所以我们被禁止在那里放置类型定义。

    【讨论】:

    • 这样的决定听起来非常聪明......
    【解决方案3】:

    考虑使用of 而不是in

    for (const role of roles) {
      const isRole = roles.includes(roles)
    }
    

    【讨论】:

    • 这并不能解决问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    • 1970-01-01
    相关资源
    最近更新 更多