I have an array of given union type, then wants to check if a string from a superset of the union type is contained in the array (runtime check):
The biggest problem is how to handle all possible values that are not ConfigurationKeys
without explicitly checking each one. I named them Configuration as it's very common scenario.
You can hide logic behind your own guard function that tells compiler: I can handle type checks, trust me. It's recognized by value is ConfigurationKeys
return type.
Code example (live):
type ConfigurationKeys = "foo" | "bar";
function isConfiguration(value: string): value is ConfigurationKeys {
const allowedKeys: string[] = ["foo", "bar"];
return allowedKeys.indexOf(value) !== -1;
}
const key: string = "alien" // Rather: some random function
if (isConfiguration(key)) {
// key => ConfigurationKeys
} else {
// key => string
}
I found writing own guard functions as very clean solution to work with Union types. Sometimes type casting is still needed, but here you hide casting and logic within single piece of code.
Reference: