Regex syntax errors caught at compile time
Catch malformed regular expression literals with tsc, and test the separate runtime path for patterns passed to the RegExp constructor.
A parser accepts ticket IDs such as BUG-42 and TASK-3. You edit the regex and leave an extra closing parenthesis in the literal. If your build skips TypeScript checking, you may hear about the typo when a test tries to load the file.
Type-check the literal
Save this as broken.ts. The first closing parenthesis ends the group of ticket prefixes. The second has no opening partner.
const ticketId = /^(BUG|TASK))-\d+$/;
console.log(ticketId.test("BUG-42"));Use a scratch project with TypeScript 5.5 or later and no tsconfig.json. Run pnpm exec tsc --noEmit broken.ts to see TS1508 point at the extra ).
Remove that parenthesis and save the result as fixed.ts.
const ticketId = /^(BUG|TASK)-\d+$/;
console.log(ticketId.test("BUG-42"));
console.log(ticketId.test("TASK-"));Run pnpm exec tsc fixed.ts and then node fixed.js. The script prints true and false.
Use --noEmit in the project check when a separate tool produces JavaScript. A type checker can catch malformed syntax, but a well-formed pattern can still match the wrong text. Keep tests for the inputs you accept and for the nearest miss, such as a prefix and hyphen with no digits.
Validate patterns read as strings
The TypeScript regex check applies to literals. Pass the same broken pattern to new RegExp and the type checker checks that the argument is a string. The regex parser runs when JavaScript calls the constructor.
const ticketId = new RegExp(String.raw`^(BUG|TASK))-\d+$`);
console.log(ticketId.test("BUG-42"));Save this as pattern.ts. Run pnpm exec tsc --target es2020 pattern.ts and then node pattern.js. The compile succeeds, and Node throws a SyntaxError before reaching the log.
Use a literal when the pattern lives in source code. If a pattern comes from configuration, construct the regex at the point where you load the configuration. Report a syntax error with the name of the setting so the person editing it can find the input that needs fixing.