我想检查字符串是否具有与联合类型匹配的前缀,例如:
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)
}
答案 0 :(得分:2)
我认为目前仅内置Typescript类型是不可能的。 https://github.com/Microsoft/TypeScript/issues/6579,以供参考:How to define a regex-matched string type in Typescript?
答案 1 :(得分:2)
在当前版本的TypeScript中,您无法剖析联合类型。对于您的问题,我建议使用enum
s这样的方法:
enum Prefixes {
"ABC",
"DEF",
"GHI"
}
const hasPrefix = (str: string): boolean => Prefixes[str.substr(0, 3)] !== 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
Here's具有上述代码的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): 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该代码的游乐场。