How to properly type a regex when destructuring?

  • 0
    How to properly type a regex when destructuring?
    const [a, b, c, d, f, g = ''] = value.match (/ \ d + / g);
    TS swears at Type 'RegExpMatchArray | null 'is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.
    JavaScript Evan Pope, Jun 9, 2020

  • 2 Answers
  • 0
    Are you sure it won't be null?

    If yes, then you can simply report it to the compiler:

    const [a, b, c, d, f, g= ''] = value.match(/\d+/g)!;




    But for good reason, it should be checked for null. At least like this:

    const [a, b, c, d, f, g= ''] = value.match(/\d+/g) || [];
    Anonymous

  • 0
    Well, it tells you in plain text: match can return null and then an error will occur at runtime.



    Or like this:
    const [a, b, c, d, f, g= ''] = value.match(/\d+/g) || [];
    Or, if you are 146% sure that match will definitely find something:
    const [a, b, c, d, f, g= ''] = value.match(/\d+/g) as string[];
    Isaiah Ingram

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!