TypeScript: 可选合并类型

7

我有类型 a 和类型 b,但这应该适用于任意数量的类型。

type a = {
    first: number
}

type b = {
    second: string
    third: string
}

我想创建一个类型,可以选择性地合并所有这些类型,所以如果它有second字段,它也应该有third字段,但不必同时拥有它们两个。

好的:

const aa = {
     first: 1,
     second: "hi",
     third: "hello"
}

const ab = {
     first: 1
}

const ac = {
     second: "hi",
     third: "hello"
}

不佳:

const bb = {
     first: 1,
     second: "hi"
}

我该如何定义这样一种类型?

你正在寻找异或合并吗? - MacD
2个回答

11

谢谢,这非常有帮助!只是EitherOrBoth类型是否可以应用于两种以上的类型? - The Cubear Guy
1
是的,你可以将另一个EitherOrBoth作为类型参数传递。请查看链接问题以获取示例。 - Lesiak
谢谢!这解决了我的问题。我已经检查了链接的问题,CombinationOf 类型是否可以应用于任意数量的类型? - The Cubear Guy
1
链接问题中的定义有最多四种类型,但如果需要更多,很容易进行扩展。 - Lesiak

0

我不确定你是否能够这样做。这是我会做的:

在定义变量时,您可以使用“|”运算符。

type a = {
    first: number
}

type b = {
    second: string
    third: string
}

const test: a | b ={ first: 3, second: 'string'}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接