我有类型 a
并输入 b
,但这应该适用于任何数量的类型。
type a = {
first: number
}
type b = {
second: string
third: string
}
我想创建一个可以选择合并所有这些类型的类型,所以如果它有 second
字段,它应该有 third
field 也是,但不必同时拥有它们:好的:
const aa = {
first: 1,
second: "hi",
third: "hello"
}
const ab = {
first: 1
}
const ac = {
second: "hi",
third: "hello"
}
坏的:const bb = {
first: 1,
second: "hi"
}
我怎么能定义这样的类型?
最佳答案
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>
查看更详细的示例:Can Typescript Interfaces express co-occurrence constraints for propertiesPlayground link
关于TypeScript:可选的合并类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63854469/