The ability to dissect a union type is not currently available in the latest version of TypeScript. A recommended solution for this issue involves utilizing enum
s, as demonstrated below:
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 link to view and test the code.
Based on your query, it seems that you are interested in dynamically checking prefixes, as indicated by the characters (?). To address this, a solution incorporating a Set
data structure was devised. See example code snippet below:
// Set data structure ensures uniqueness
type Prefix = string;
const prefixes: Set<Prefix> = new Set();
prefixes.add("ABC");
prefixes.add("ABC");
prefixes.add("DEF");
prefixes.add("GHI");
// Double addition of ABC does not affect uniqueness
console.log(prefixes);
// Typeguard function
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
}
View the code playground here.