In JavaScript, using named capture groups is pretty convenient:
const auth = 'Bearer AUTHORIZATION_TOKEN'
const { groups: { token } } = /Bearer (?<token>[^ $]*)/.exec(auth)
console.log(token) // "AUTHORIZATION_TOKEN"
When I try that in typescript, it doesn't compile because groups
could be null
. If I put a !
after exec(...)
, it just kicks the can: token
could be undefined.
In typescript, is there any way I can destructure the regex like above?
It doesn't compile because
groups
could benull
.
No, it doesn't compile because .exec()
can return null
, when the regex does not match. Attempting to access a property like .groups
on that will cause a TypeError: Cannot read properties of null.
You'll need a fallback value (using nullish coalescing and default initialisers) to destructure in that case:
const { groups: {token} = {} } = /Bearer (?<token>[^ $]*)/.exec(auth) ?? {}
or simpler with optional chaining:
const { token } = /Bearer (?<token>[^ $]*)/.exec(auth)?.groups ?? {}