I've been trying to create a function where the function's parameter is a union made from two other unions. I want it so that depending on the string passed into the parameter, a different function fires accordingly. Something like this:
type Type1 = "a" | "b" | "c";
type Type2 = "x" | "y" | "z";
function doSomething(param: Type1 | Type2) {
// if param is a part of the "Type1" union
functionForTypeOne();
}
doSomething("z");
I searched through the internet and the docs and I couldn't find a way to do this runtime type checking. I found some "solutions" for type checking, but they were all written for object types, not strings and unions.
In basic javascript, I could create a const array and check if the string is found inside the array, like so:
const type1 = ["a", "b", "c"];
const type2 = ["x", "y", "z"];
function doSomething(param) {
if (type1.includes(param))
functionForTypeOne();
}
Doing this in TypeScript is kind of a solution, but since I need to create unions from these consts, it feels very inefficient, and doesn't allow me to use the type checking features of the language. I was curious if anyone has a solution for this that I possibly overlooked, or if this is the only way for me to get around my problem.