type Extracted<T> = T extends `${string}${'*('}${infer A}${')+'}${string}${'*('}${infer A}${')+'}${string}` ? A : never
type Result1 = Extracted<'g*(a12)+gggggg*(h23)+'> // 'a12' | 'h23'
type Result2 = Extracted<'g*(a12)+gggggg*(h23)+gggggg*(5hgf)+'> // 'a12' | 'h23' but without '5hgf'
The goal is to extract all literals from a string with a specific pattern. In the given code, I want to extract literals that start with '*('
and end with ')+'
'. Therefore, type Result1 = 'a12' | 'h23'
.
The challenge lies in handling situations where a string can have multiple matched-pattern-literals, and it's unclear how to make typescript extract all of them.
In the provided example, Typescript only extracts two literals because the pattern is repeated twice:
${string}${'*('}${infer A}${')+'}
. Even with type z=Extracted<'g*(a12)+gggggg*(h23)+gggggg*(5hgf)'+>
, the result remains as type Result2 = 'a12' | 'h23'
. Ideally, the output should include '5hgf'
as well.
Is there a way to instruct typescript to iterate through the string and capture all desired literals?
Appreciate any assistance!