Given two interfaces:
type I1 = {
a: string
b: string
c: number
}
type I2 = {
a: string
b: string
d: string
}
I need to create a type which only has properties which are not shared by the two interfaces.
type Result = XOR<I1, I2>
// should become
type Result = {
c: number
d: string
}
I tried this:
type XOR<T1, T2> = {
[K in keyof (T1 & T2)]: T1[K & keyof T1] | T2[K & keyof T2]
// ^^ I need something like "not in" here
}
But I am not sure how to only map over keys which are not in both T1
and T2
.
CodePudding user response:
type XOR<A, B> = {
[K in Exclude<keyof A | keyof B, keyof A & keyof B>]: K extends keyof A ? A[K] : K extends keyof B ? B[K] : never;
};
Exclude keyof A ∩ keyof B from keyof A ∪ keyof B to get the keys that are only in either A or B. Then just get the right value from A or B for the key.
Oh, I haven't had my afternoon coffee yet...
type XOR<A, B> = Omit<A & B, keyof A & keyof B>;