UPDATE: Bergi's answer is the more correct and typesafe way to accomplish this.
It's ugly, but something like this would work:
const auth = 'Bearer AUTHORIZATION_TOKEN'
type RegexTokenObj = { groups: { token: string } };
const { groups: { token } } = (/Bearer (?<token>[^ $]*)/.exec(auth) as unknown as RegexTokenObj)
console.log(token) // "AUTHORIZATION_TOKEN"
If you just try const { groups: { token } } = (/Bearer (?<token>[^ $]*)/.exec(auth) as RegexTokenObj)
it will yell at you that "Conversion of type 'RegExpExecArray | null' to type 'RegexTokenObj' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
" Thus we can convert to unknown
before casting as the type we know/expect it will be. That said, we are overriding the type system here, so we should be certain we are confident that we are correct in doing so, so be careful.