Ternary operator produces a union of objects that do not satisfy overloaded function

20 Views Asked by At

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);
}

Playground

1

There are 1 best solutions below

0
Serhii Holinei On

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

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 works too
function test(foo: number | string, bar: boolean) {
    if (typeof foo === 'string') {
        func({ foo, bar });
    } else {
        func({ foo })
    }
}