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 accepted answer uses type assertions/casting but from the comments it appears the OP went with a solution using find
that works differently. I prefer that solution also, so here's how that can work:
const configKeys = ['foo', 'bar'] as const;
type ConfigKey = typeof configKeys[number]; // "foo" | "bar"
// Return a typed ConfigKey from a string read at runtime (or throw if invalid).
function getTypedConfigKey(maybeConfigKey: string): ConfigKey {
const configKey = configKeys.find((validKey) => validKey === maybeConfigKey);
if (configKey) {
return configKey;
}
throw new Error(`String "${maybeConfigKey}" is not a valid config key.`);
}
Note that this can guarantee that a string is a valid ConfigKey
both at runtime and compile time.