How to properly type a regex when destructuring?
-
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 -
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 -
Well, it tells you in plain text:
match
can returnnull
and then an error will occur at runtime.
Or like this:
Or, if you are 146% sure thatconst [a, b, c, d, f, g= ''] = value.match(/\d+/g) || [];
match
will definitely find something:const [a, b, c, d, f, g= ''] = value.match(/\d+/g) as string[];
Isaiah Ingram
2 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!