使用TypeScript对联合类型进行参数检查

3

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

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)
}

1
我猜问题在于如何将“前缀”类型与内置方法一起使用,对吧?似乎只有自定义逻辑,就像你评论中所说的那样,才适用(类型为字符串,然后进行检查)。 - Georgy
1
为什么您想要检查类型而不是仅检查前缀字符串数组?您的使用场景是什么? - Mu-Tsun Tsai
2个回答

2

2
在当前版本的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


最初的回答
根据您的问题,您似乎对动态检查前缀(...字符暗示了这一点(?))感兴趣。这让我想到了使用Set数据类型的解决方案。考虑以下示例:
以下是上述代码的TypeScript playground链接:这里
// 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
}

Here's the playground for that code.


1
在你的第一个代码片段中,使用 typeof Prefixes[str.substr(0, 3)] !== "undefined" 会更加合适 - Nicolas
1
@Nicolas,感谢您的反馈,我已经更新了第一个示例。 - Alex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接