0

I'm trying to make a typescript function that takes an argument that matches one of two conditions:

type A = {
  x: string
}

type B = {
 y: string
}

function testFunc(param: A | B) {
  ...
}

however typescript lets me call the function with both keys:

testFunc({x: "x", y: "y"})

Shouldn't the union type make it so that this function requires A or B?

Playground demonstrating the issue here

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
john_ryan
  • 1,557
  • 1
  • 16
  • 34

1 Answers1

1

You can do this with function overloads:

type One = {
    x: string
}

type Two = {
    y: string
}


function test(props: One): void;
function test(props: Two): void;
function test(props: (One | Two)) {
    console.log(props)
}

test({
    x: 'a',
}) // ok

test({
    y: 'f'
}) // ok
test({
    x: 'a',
    y: 'f'
}) // error

Playground link

apokryfos
  • 38,771
  • 9
  • 70
  • 114