TypeScript:可选的合并类型

The*_*Guy 4 typescript typescript-typings

我有 typea和 type b,但这应该适用于任何数量的类型。

type a = {
    first: number
}

type b = {
    second: string
    third: string
}
Run Code Online (Sandbox Code Playgroud)

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

好的:

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

const ab = {
     first: 1
}

const ac = {
     second: "hi",
     third: "hello"
}
Run Code Online (Sandbox Code Playgroud)

坏的:

const bb = {
     first: 1,
     second: "hi"
}
Run Code Online (Sandbox Code Playgroud)

我怎么能定义这样的类型?

Les*_*iak 6

type None<T> = {[K in keyof T]?: never}
type EitherOrBoth<T1, T2> = T1 & None<T2> | T2 & None<T1> | T1 & T2

type abcombined = EitherOrBoth<a,b>
Run Code Online (Sandbox Code Playgroud)

请参阅更详细的示例:Can Typescript Interfaces express co-occurrence constraint for properties

游乐场链接