I have a function with a return type that looks something like the following:
type FuncReturns = TypeA | [any, TypeB];
where...
interface TypeA {
name: string;
count: number;
}
interface TypeB {
color: string;
volume: number;
edges: number;
}
const myAwesomeFunc = (val : string | number, obj : object = {}) : FuncReturns=>{
switch(typeof val){
case "string" : {
return {
name: val,
count: 1
}
} case "number" : {
return [obj, {
color: "blue",
volume: 6,
edges: 6
}]
} default {// should never be used in this way
throw new Error("This is nonsense.")
}
}
}
... should be unpack-able (destructurable) both like this...
const {name, count} = myAwesomeFunc(someValue);
... and like this...
const [object, {color, volume, edges}] = myAwesomeFunc(someOtherValue);
Based on some internal logic, the function may return an object, TypeA, which I would like to unpack or an array, TypeB, which I would also like to unpack. Unfortunately, rather than accepting the array unpacking operator as one of the possible methods that could be applied to the return type, I end up with an error that states the union type is not an array type. I can think of several workarounds for my use case, but I'd like to know if there is an established way to solve this problem.
NOTE: As alekxsor duly noted, there are really only two branches I want the function to travel down: (1) string val to return object and (2) number val to return array. The optimal solution would enable typechecking such that when provided a string, the return type expected would be an object and so on.