Skip to content

Commit 97cb27a

Browse files
author
XLor
authored
feat(types): add MagicRegExpMatchArray utility type (#12)
1 parent c1d6806 commit 97cb27a

File tree

2 files changed

+27
-9
lines changed

2 files changed

+27
-9
lines changed

src/index.ts

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,29 @@ export const createRegExp = <Value extends string, NamedGroups extends string =
1515
export * from './core/flags'
1616
export * from './core/inputs'
1717

18+
type ExtractNamedGroups<T extends MagicRegExp<string, string>> = T extends MagicRegExp<
19+
string,
20+
infer V
21+
>
22+
? V
23+
: never
24+
25+
export type MagicRegExpMatchArray<T extends MagicRegExp<string, string>> = Omit<
26+
RegExpMatchArray,
27+
'groups'
28+
> & {
29+
groups: Record<ExtractNamedGroups<T>, string | undefined>
30+
}
31+
1832
// Add additional overload to global String object types to allow for typed capturing groups
1933
declare global {
2034
interface String {
21-
match<T extends string>(
22-
regexp: MagicRegExp<any, T>
23-
): (Omit<RegExpMatchArray, 'groups'> & { groups: Record<T, string | undefined> }) | null
24-
matchAll<T extends string>(
25-
regexp: MagicRegExp<any, T>
26-
): IterableIterator<
27-
Omit<RegExpMatchArray, 'groups'> & { groups: Record<T, string | undefined> }
28-
>
35+
match<T extends string, RegExp extends MagicRegExp<any, T>>(
36+
regexp: RegExp
37+
): MagicRegExpMatchArray<RegExp> | null
38+
39+
matchAll<T extends string, RegExp extends MagicRegExp<any, T>>(
40+
regexp: RegExp
41+
): IterableIterator<MagicRegExpMatchArray<RegExp>>
2942
}
3043
}

test/index.test.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { expect, it, describe } from 'vitest'
22
import { expectTypeOf } from 'expect-type'
33

4-
import { anyOf, char, createRegExp, exactly, global, digit } from '../src'
4+
import { anyOf, char, createRegExp, exactly, global, digit, MagicRegExpMatchArray } from '../src'
55
import { createInput } from '../src/core/internal'
66

77
describe('magic-regexp', () => {
@@ -71,6 +71,11 @@ describe('inputs', () => {
7171
"test2": "baz",
7272
}
7373
`)
74+
75+
const regexp = createRegExp(pattern)
76+
expectTypeOf('fobazzer'.match(regexp)).toMatchTypeOf<MagicRegExpMatchArray<
77+
typeof regexp
78+
> | null>()
7479
expectTypeOf('fobazzer'.match(createRegExp(pattern))?.groups).toMatchTypeOf<
7580
Record<'test' | 'test2', string | undefined> | undefined
7681
>()

0 commit comments

Comments
 (0)