Dan*_*lan 7 regex destructuring typescript named-captures
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
可能是未定义的。
在打字稿中,有什么方法可以像上面那样解构正则表达式吗?
它无法编译,因为
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)
归档时间: |
|
查看次数: |
885 次 |
最近记录: |