如何解构命名捕获组?

Dan*_*lan 7 regex destructuring typescript named-captures

在 JavaScript 中,使用命名捕获组非常方便

const auth = 'Bearer AUTHORIZATION_TOKEN'
const { groups: { token } } = /Bearer (?<token>[^ $]*)/.exec(auth)
console.log(token) // "AUTHORIZATION_TOKEN"
Run Code Online (Sandbox Code Playgroud)

当我在打字稿中尝试时,它无法编译,因为groups可能是null. 如果我放一个!after exec(...),它只会踢罐头:token可能是未定义的。

在打字稿中,有什么方法可以像上面那样解构正则表达式吗?

Ber*_*rgi 7

它无法编译,因为groups可能是null.

不,它不会编译,因为当正则表达式不匹配时.exec()可以返回, 。null尝试访问类似的属性.groups将导致TypeError: Cannot readproperties of null

在这种情况下,您需要一个后备值(使用空合并和默认初始化程序)来解构:

const { groups: {token} = {} } = /Bearer (?<token>[^ $]*)/.exec(auth) ?? {}
Run Code Online (Sandbox Code Playgroud)

或更简单的可选链接

const { token } = /Bearer (?<token>[^ $]*)/.exec(auth)?.groups ?? {}
Run Code Online (Sandbox Code Playgroud)