Typescript中的类型可以定义为包含字符的组合吗?

让我通过示例进行解释。

在名为Component的字段中,您应该可以使用以下值:“ M”,“ B”,“ A”。

因此,您先进行以下定义: type Component = "M" | "B" | "A";

到目前为止,一切都很好。但是应该也可以将这些组合在一起,如下所示: const MyComponent : Component = "MB"; 要么 const MyComponent : Component = "BA";

如何定义?

wly1zwss 回答:Typescript中的类型可以定义为包含字符的组合吗?

当前无法使用TypeScript进行此操作,但是您可以使用RegEx验证这样的字符串,以下线程提供了如何执行此操作的示例: How can I split a string into segments of n characters?

您也可以使用此正则表达式:

let value = 'MBA';

// string length 1-3 and contains M,B,A combinations
let validatorRegEx = /^([M|B|A]{1,3}$)/i; 
if(validatorRegEx.test(value)) {
    // code ...
}
,

简单地为您的数据找到一个接口-看来您拥有一组简单的小值作为Component属性的域数据。所以也许您应该扩展您的类型(联合):

type Component = "M" | "B" | "A" | "MA"

您对引入枚举(字符串)有何看法?

enum Direction {
    A: "A",B: "B",M: "M",AB: "AB",// more values
}

最后-不要将数据类型视为验证器。因此,也许在您的情况下,您应该只使用简单的“字符串”类型并在需要时或在初始化时对其进行验证。

,

从TypeScript 4.1开始,可以使用template literal types。 例如:

type Component = "M" | "B" | "A";
type ComponentCombination = `${Component}${Component}`;

const comb: ComponentCombination = "MB";
本文链接:https://www.f2er.com/3130300.html

大家都在问