我在 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
工作。