My input input is an array of strings lines
. I would like to write code like the following in TypeScript.
lines
.filter((line:string) => line.match(/resource "[^"] "/))
.map((line:string) => line.match(/resource "([^"] "/)[1])
Frankly, I'm a little lost on how to accomplish this in TypeScript, and these are some of the reasons.
- I know that at runtime the second
match
won't benull
and will have captured something into slot[1]
, but the TypeScript compiler can't seem to figure this out and nags me. - I'm able to work around it with a second
map
operation that uses a ternary operator?
to check for null or empty arrays, and that actually compiles and runs fine. But the, the linter complains in a Git pre-commit hook, which tells me I'm on the wrong track.
What is the right track? What is the "correct" way to do this in TypeScript? Thanks!
CodePudding user response:
Match all the strings first, using optional chaining for brevity, then filter later by whether there was a match or not.
const matches = lines
.map(line => line.match(/resource "([^"] ")/)?.[1])
.filter(Boolean) as string[];
But your matching of /resource "([^"] "/
looks a bit suspicious - did you really want to exclude the first "
and include the second? Or might you have wanted /resource "([^"] )"/
?