【问题标题】:Ban Indexable Types in TypeScript在 TypeScript 中禁止可索引类型
【发布时间】:2020-08-01 17:14:23
【问题描述】:

我正在尝试在 tslint.yml 中搜索 tslint 规则,该规则将标记任何使用 Indexable Types(例如 { [key: string] : string })来代替使​​用 TypeScript 记录(例如 Record<string, string>),但没有运气时刻。

我遇到了一个名为 Ban-Types 的 tslint 规则,它禁止匹配给定正则表达式的类型。我已经尝试了以下

tslint.yml
  ban-types: [
    true,
    [ "{\s*\[\s*(\S+)\s*:\s*(.+)\s*\]\s*:\s*(.+)\s*}",
      "Do not use indexable types (i.e. { [index: A] : B } ). Use Record<A, B> instead." ],
  ]

但它给出了这个错误:

unknown escape sequence at line 23, column 10:
        [ "{\s*\[\s*(\S+)\s*:\s*(.+)\s*\]\s*: ... 
             ^ in /path/to/tslint.yml

我再次尝试使用以下正则表达式:

tslint.yml
  ban-types: [
    true,
    [ "\\{\\s*\\[\\s*(\\S+)\\s*:\\s*(.+)\\s*\\]\\s*:\\s*(.+)\\s*\\}",
      "Do not use indexable types (i.e. { [index: A] : B } ). Use Record<A, B> instead." ],
  ]

没有抛出任何异常,但无法检测可索引类型。

规则的实现可以在here找到,如果有帮助的话。

【问题讨论】:

  • 正则表达式默认锚定在您引用的代码中,因此您需要".*\\{\\s*\\[\\s*(\\S+)\\s*:\\s*(.+)\\s*\\]\\s*:\\s*(.+)\\s*\\}.*"

标签: regex typescript yaml tslint


【解决方案1】:

这对你有用吗?

    \{\s*\[\s*\w+\s*:\s*\w+\s*\]\s*:\s*\w*\s*\}

【讨论】:

  • 不起作用,它会抛出异常“未知转义序列”。转义两次(即\\{)确实可以防止错误,但仍然无法检测到。
猜你喜欢
  • 1970-01-01
  • 2021-04-05
  • 2021-12-30
  • 2021-11-20
  • 1970-01-01
  • 2019-08-10
  • 2021-02-22
  • 2017-06-11
相关资源
最近更新 更多