G
G
gofi2020-11-13 10:51:09
JavaScript
gofi, 2020-11-13 10:51:09

How to correctly type a regular expression during destructuring?

How to correctly type a regular expression during 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.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lynn "Coffee Man", 2020-11-13
@gofi

Are you sure it won't be null?
If yes, then you can just tell the compiler about it:

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

But on good it would be necessary to check for null. At least like this:
const [a, b, c, d, f, g= ''] = value.match(/\d+/g) || [];

A
Aetae, 2020-11-13
@Aetae

Well, you are told in plain text: it matchcan return nulland then an error will occur during execution.
Either like this:

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

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question