Skip to content

Commit

Permalink
fix: correctly merge group generics for .and and .or
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe committed Jul 17, 2022
1 parent 36c29f3 commit b2b7876
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
11 changes: 7 additions & 4 deletions src/core/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@ import type { InputSource } from './types/sources'

export interface Input<V extends string, G extends string = never> {
/** this adds a new pattern to the current input */
and: <I extends InputSource<string, G>, Groups extends string = never>(
and: <I extends InputSource<string, any>>(
input: I
) => Input<`${V}${GetValue<I>}`, G | Groups>
) => Input<`${V}${GetValue<I>}`, G | (I extends Input<any, infer NewGroups> ? NewGroups : never)>
/** this provides an alternative to the current input */
or: <I extends InputSource<string, G>, Groups extends string = never>(
or: <I extends InputSource<string, any>>(
input: I
) => Input<`(${V}|${GetValue<I>})`, G | Groups>
) => Input<
`(${V}|${GetValue<I>})`,
G | (I extends Input<any, infer NewGroups> ? NewGroups : never)
>
/** 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) */
after: <I extends InputSource<string>>(input: I) => Input<`(?<=${GetValue<I>})${V}`, G>
/** this is a positive lookahead */
Expand Down
11 changes: 10 additions & 1 deletion test/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { expect, it, describe } from 'vitest'
import { expectTypeOf } from 'expect-type'

import { anyOf, char, createRegExp, exactly, global } from '../src'
import { anyOf, char, createRegExp, exactly, global, digit } from '../src'
import { createInput } from '../src/core/internal'

describe('magic-regexp', () => {
Expand Down Expand Up @@ -74,6 +74,7 @@ describe('inputs', () => {
expectTypeOf('fobazzer'.match(createRegExp(pattern))?.groups).toMatchTypeOf<
Record<'test' | 'test2', string | undefined> | undefined
>()

// @ts-expect-error
'fobazzer'.match(createRegExp(pattern))?.groups.other

Expand All @@ -86,5 +87,13 @@ describe('inputs', () => {
`)
expectTypeOf(match.groups).toMatchTypeOf<Record<'test' | 'test2', string | undefined>>()
}

''.match(
createRegExp(
anyOf(anyOf('foo', 'bar').as('test'), exactly('baz').as('test2')).and(
digit.times(5).as('id').optionally()
)
)
)?.groups?.id
})
})

0 comments on commit b2b7876

Please sign in to comment.