Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to cast regex groups into Typescript types?

Suppose I have the following string:

"A D"

And I apply the following RegExp:

/([AB]) *([CD])/

This will either return null, or return an array of strings representing the groups. The first group will always be either "A" or "B", in my case "A". The second group will always be "C" or "D".

As such I would like the following:

const str = 'A    D'
const groups = new RegExp('([AB]) *([CD])').exec(str);
return groups[1] === 'Q'

This should give me a typescript error, but it doesn't. I want it to give me ts(2367), this condition will always return 'false' since types groups[1]: "A" | "B" and "Q" have no overlap.

Is there nice way I can have typescript pull the group types out of my regexp?

like image 429
BenMcLean981 Avatar asked Oct 27 '25 15:10

BenMcLean981


1 Answers

Not really - TypeScript doesn't try to interpret patterns, and the shape of exec is:

exec(string: string): RegExpExecArray | null;

where RegExpExecArray is:

interface RegExpExecArray extends Array<string> {
    index: number;
    input: string;
}

.match isn't any better.

If your pattern, when executed, produces an output of certain types, you'll have to specify them explicitly in addition to the pattern, eg:

const groups = new RegExp('([AB]) *([CD])').exec(str);
if (groups) {
    const typedGroups = [...groups] as [string, 'A' | 'B', 'C' | 'D'];

It's not very pretty, but there aren't really any good options here.

like image 182
CertainPerformance Avatar answered Oct 29 '25 06:10

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!