首页 > 解决方案 > 有没有办法解构一个 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的类型。secondthirdstring

我只想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|booleanlet

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

工作。

标签: javascriptnode.jstypescriptdestructuringobject-destructuring

解决方案


推荐阅读