繁体   English   中英

针对联合类型的打字稿参数检查

[英]Typescript argument check against a union type

我想检查一个字符串是否有一个匹配联合类型的前缀,例如:

type Prefix = "ABC" | "DEF" | "GHI" ...;
const hasPrefix = (str: string): boolean => {
   // I want to check the first 3 characters of the string
   // And see if it matches any of the Prefix
   // Something like
   //  if (str.substr(0, 3) === Prefix)
}

我认为目前仅使用内置的 Typescript 类型是不可能的。 https://github.com/Microsoft/TypeScript/issues/6579和参考提案: How to define a regex-matched string type in Typescript?

在当前版本的 TypeScript 中,您无法剖析联合类型。 对于您的问题,我会推荐一种使用enum的方法,如下所示:

enum Prefixes {
    "ABC",
    "DEF",
    "GHI"
}

const hasPrefix = (str: string): boolean => Prefixes[str.substr(0, 3) as any] !== "undefined";

console.log(hasPrefix("123")); // false
console.log(hasPrefix("ABC")); // true
console.log(hasPrefix("DEF")); // true
console.log(hasPrefix("GHI")); // true
console.log(hasPrefix("GHII"));// true

const data = "ABC123";         // ABC123

console.log(hasPrefix(data));  // true
console.log(data);             // still ABC123

这是上述代码的 TypeScript 游乐场。


从你的问题来看,你似乎对检查前缀的动态方式感兴趣( ...字符暗示这个(?))。 这让我思考并想出了一个使用Set数据类型的解决方案。 考虑这个例子:

// Set data type ensures only uniques
type Prefix = string;
const prefixes: Set<Prefix> = new Set();

prefixes.add("ABC");
prefixes.add("ABC");
prefixes.add("DEF");
prefixes.add("GHI");

// No doubles here so we're good (note the double added ABC string)
console.log(prefixes);

// the typeguard
const hasPrefix = (str: any): str is Prefix => typeof str === "string" ? prefixes.has(str.substr(0, 3)): false;

console.log(hasPrefix(100));   // false
console.log(hasPrefix(0));     // false
console.log(hasPrefix(false)); // false
console.log(hasPrefix(true));  // false
console.log(hasPrefix(""));    // false
console.log(hasPrefix("123")); // false
console.log(hasPrefix("ABC")); // true
console.log(hasPrefix("DEF")); // true
console.log(hasPrefix("GHI")); // true
console.log(hasPrefix("GHII"));// true

const data = "ABC123";         // ABC123

if (hasPrefix(data)) {
    console.log(hasPrefix(data));  // true
    console.log(data);             // still ABC123
}

这是该代码的游乐场。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM