I have an overloaded function that accepts an object with different parameters. I create an object using the ternary operator and pass it on.
However, the created object arg is a union of objects that my function doesn't want to accept.
How to create a correct union of objects? I don't want to change the overloaded function.
function func(a: { foo: number }): void
function func(a: { foo: string, bar: boolean}): void
function func(a: unknown) {
console.log(a);
}
// this works fine
func({ foo: 42 })
func({ foo: 'hello', bar: true })
// this doesn't
function test(foo: number | string, bar: boolean) {
const arg = typeof foo === 'string' ? { foo, bar } : { foo };
func(arg);
}
Okay, I now understand my question wasn't correct. I was able to get a "perfect" union, but it didn't work for me.
Instead of passing a union as a parameter, I needed to conditionally invoke the function:
Playground