I have a situation where I need a function to accept a variety of different types. They will be separated by type guards within the function. So I am using a Union Type like this:
function(param: TypeA | TypeB): void {
let callback: (param: TypeA | TypeB): void = () => {};
if (isTypeA(param)) {
callback = doSomethingWithTypeA;
} else if (isTypeB(param)) {
callback = doSomethingWithTypeB;
}
return callback(param);
}
Where the function doSomethingWithTypeA
only accepts typeA and so on.
As you can see, always writing out (TypeA | TypeB)
is very verbose, especially since it's more than two types in my actual code.
Is there some way to create an interface that is (TypeA | TypeB)
?
Or is there some other way to achieve this?
Use type aliases:
How about creating an interface:
Then you can check it in the method: