In TypeScript what is the idiomatic way to filter an array of strings with a regular expression AND map to capturing groups?

Viewed 78

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.

  1. I know that at runtime the second match won't be null and will have captured something into slot [1], but the TypeScript compiler can't seem to figure this out and nags me.
  2. 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!

1 Answers

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 "([^"]+)"/?

Related