javascript - 有没有办法解构一个 regex.groups 对象,输入一个元素 string|boolean 而不是推断的字符串?
问题描述
我在 TypeScript 中有一个 RegExp,其中有一些组
我试图将其破坏为具有不同名称的变量。
这就是它的外观:
let rx = /(?<one>.)(?<two>.)?(?<three>.)/; // example regex, mine is bigger and more complex
let {one:first, two: second, three:third} = rx.groups;
second = !!second;
它推断和first
的类型。second
third
string
我只想second
保持“第二组在场”状态,second
所以我确实second = !!second
要得到 a boolean
,但这不会让我这样做,因为second
是 a string
。所以我希望second
能够保持一个布尔值。(类型string|boolean
:)
我知道我可以让它与更多行一起工作:
let second:string|boolean;
let {one:first,three:third} = rx.groups;
({two:second} = rx.groups);
second = !!second;
我还可以创建一个只保存布尔值的新变量,如下所示:
let {one:first,two:second,three:third} = rx.groups;
let secondBoolean = !!second;
但是没有办法让它在破坏语句
中更改boolean
或设置它的类型吗?
两者都不string|boolean
let
let { one: first, two: second, three:third }: { two: string | boolean, [key: string]: string } = rx.groups;
// Property 'two' is missing in type '{ [key: string]: string; }' but required in type '{ [key: string]: string; two: string | boolean; }'.
// AND Property 'two' of type 'string | boolean' is not assignable to string index type 'string'.
也不
let {one: first, two:second, three:third}: {one:string, two:second|boolean, three:string} = rx.groups;
// Type '{ [key: string]: string; }' is missing the following properties from type '{ one: string; two: string | boolean; three: string; }': one, two, three
工作。
解决方案
推荐阅读
- python - 基于多级列过滤行
- c# - 错误 C#:OpenQA.Selenium.ElementNotInteractableException:'元素不可交互
- android - 当您将应用程序置于后台并返回时,OnBackPressedCallback 第一次不起作用
- php - 将 Array 对象的索引(键)与数组的索引(键)相关联 (PHP)
- java - CDI:注入由依赖项生成的 bean
- c++ - 如果有符号整数位移是算术的,如何在编译时检查?
- javascript - 防止 gatsby 站点在页面更改时重新安装图像
- html - 带有段落的 HTML CSS 图像
- react-native - 复活的 SharedValue 更改时调用 React Native 代码
- python-3.x - chrome中的python在点击时自动登录?