typescript中的异或类型

typescript中的异或类型,typescript,typescript-typings,Typescript,Typescript Typings,我正在尝试创建一个typescript函数,该函数接受一个匹配以下两个条件之一的参数: type A = { x: string } type B = { y: string } function testFunc(param: A | B) { ... } 但是,typescript允许我使用两个键调用函数: testFunc({x: "x", y: "y"}) union类型不应该使此函数需要A或B吗 您可以通过函数重载来解决此问题:

我正在尝试创建一个typescript函数,该函数接受一个匹配以下两个条件之一的参数:

type A = {
  x: string
}

type B = {
 y: string
}

function testFunc(param: A | B) {
  ...
}
但是,typescript允许我使用两个键调用函数:

testFunc({x: "x", y: "y"})
union类型不应该使此函数需要AB吗


您可以通过函数重载来解决此问题:

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

我认为这可能很有趣: