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 "([^"]+"/))
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
nulland will have captured something into slot
, but the TypeScript compiler can’t seem to figure this out and nags me.
- I’m able to work around it with a second
mapoperation 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!
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 "([^"]+")/)?.) .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
Answered By – CertainPerformance
Answer Checked By – Clifford M. (BugsFixing Volunteer)