打字稿中的独占或类型
Exclusive or types in typescript
我正在尝试创建一个 typescript 函数,该函数的参数符合以下两个条件之一:
type A = {
x: string
}
type B = {
y: string
}
function testFunc(param: A | B) {
...
}
但是打字稿允许我用两个键调用函数:
testFunc({x: "x", y: "y"})
联合类型不应该让这个函数需要 A or B?
演示问题的游乐场here
您可以使用函数重载来做到这一点:
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
我正在尝试创建一个 typescript 函数,该函数的参数符合以下两个条件之一:
type A = {
x: string
}
type B = {
y: string
}
function testFunc(param: A | B) {
...
}
但是打字稿允许我用两个键调用函数:
testFunc({x: "x", y: "y"})
联合类型不应该让这个函数需要 A or B?
演示问题的游乐场here
您可以使用函数重载来做到这一点:
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