Skip to content

Commit b2b7876

Browse files
committed
fix: correctly merge group generics for .and and .or
1 parent 36c29f3 commit b2b7876

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

src/core/internal.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,16 @@ import type { InputSource } from './types/sources'
44

55
export interface Input<V extends string, G extends string = never> {
66
/** this adds a new pattern to the current input */
7-
and: <I extends InputSource<string, G>, Groups extends string = never>(
7+
and: <I extends InputSource<string, any>>(
88
input: I
9-
) => Input<`${V}${GetValue<I>}`, G | Groups>
9+
) => Input<`${V}${GetValue<I>}`, G | (I extends Input<any, infer NewGroups> ? NewGroups : never)>
1010
/** this provides an alternative to the current input */
11-
or: <I extends InputSource<string, G>, Groups extends string = never>(
11+
or: <I extends InputSource<string, any>>(
1212
input: I
13-
) => Input<`(${V}|${GetValue<I>})`, G | Groups>
13+
) => Input<
14+
`(${V}|${GetValue<I>})`,
15+
G | (I extends Input<any, infer NewGroups> ? NewGroups : never)
16+
>
1417
/** this is a positive lookbehind. Make sure to check [browser support](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#browser_compatibility) as not all browsers support lookbehinds (notably Safari) */
1518
after: <I extends InputSource<string>>(input: I) => Input<`(?<=${GetValue<I>})${V}`, G>
1619
/** this is a positive lookahead */

test/index.test.ts

Lines changed: 10 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 } from '../src'
4+
import { anyOf, char, createRegExp, exactly, global, digit } from '../src'
55
import { createInput } from '../src/core/internal'
66

77
describe('magic-regexp', () => {
@@ -74,6 +74,7 @@ describe('inputs', () => {
7474
expectTypeOf('fobazzer'.match(createRegExp(pattern))?.groups).toMatchTypeOf<
7575
Record<'test' | 'test2', string | undefined> | undefined
7676
>()
77+
7778
// @ts-expect-error
7879
'fobazzer'.match(createRegExp(pattern))?.groups.other
7980

@@ -86,5 +87,13 @@ describe('inputs', () => {
8687
`)
8788
expectTypeOf(match.groups).toMatchTypeOf<Record<'test' | 'test2', string | undefined>>()
8889
}
90+
91+
''.match(
92+
createRegExp(
93+
anyOf(anyOf('foo', 'bar').as('test'), exactly('baz').as('test2')).and(
94+
digit.times(5).as('id').optionally()
95+
)
96+
)
97+
)?.groups?.id
8998
})
9099
})

0 commit comments

Comments
 (0)