In the current version of TypeScript you can't dissect a union type. For your problem I would recommend an approach using enum
s like so:
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
Here's a TypeScript playground of the above code.
Judging by your question you seem to be interested in a dynamic way to check for prefixes (the ...
characters imply this (?)). This got me thinking and came up with a solution using a Set
data type. Consider this example:
// 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.