首页 > 解决方案 > 排他或打字稿中的类型

问题描述

我正在尝试制作一个打字稿函数,该函数接受一个匹配两个条件之一的参数:

type A = {
  x: string
}

type B = {
 y: string
}

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

但是打字稿让我用两个键调用函数:

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

联合类型不应该使这个函数需要AB吗?

在这里展示问题的游乐场

标签: typescripttypescript-typings

解决方案


您可以使用函数重载来做到这一点:

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

游乐场链接


推荐阅读