I am trying to check if a given string value is a valid value at some string union type in typescript. Something like this:
export default class TypeGuard<U extends string> {
isSafe<T extends string>(candidate?: T): ((T & U) | undefined) {
if (!candidate) return undefined;
let result: T & U;
try {
result = candidate as T & U;
} catch (error) { // expect TypeError
return undefined;
}
if (!result) return undefined;
return result;
}
}
But the as operator don't works as I desired. Searching over the internet I found various "solutions" that basically creates an array with all valid values, uses this array to define the union type, and checks if the array includes the desired value. But this is not a valid solution to my case, because I don't define the union type, it is defined in an external library.
Anyone knows another alternative to perform this check?