【问题标题】:TypeScript array filter only RegExp [duplicate]仅 TypeScript 数组过滤器 RegExp [重复]
【发布时间】:2021-05-05 11:11:17
【问题描述】:

我正在尝试仅过滤 RegExp 表达式并得到一个错误。

const arr = ['test', '/test/', /test/, /test/g]; 
const regs: RegExp[] = arr.filter(str => str instanceof RegExp);
Type '(string | RegExp)[]' is not assignable to type 'RegExp[]'.
  Type 'string | RegExp' is not assignable to type 'RegExp'.
    Type 'string' is not assignable to type 'RegExp'.

example

如何通过仅获取RegExp 的列表来避免此类错误?

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

    你需要告诉 typescript 提供的回调是一个类型保护:

    const regs: RegExp[] = arr.filter((str): str is RegExp => str instanceof RegExp);
    

    Playground


    然后你也可以移除显式变量类型:

    const regs = arr.filter((str): str is RegExp => str instanceof RegExp);
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-19
    • 2023-01-02
    • 2019-06-16
    • 2019-08-11
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    相关资源
    最近更新 更多