In typescript I have the following type:
type Base = {
mandatoryProperty: number
}
Then I would like to create a Full type starting from Base that EITHER has a property1: number or property2: number, such as:
type Full = {
mandatoryProperty: number
property1: number
} | {
mandatoryProperty: number
property2: number
}
I create a Combined utility type:
type Combined<T, V> = {
[K in keyof V]: {[R in keyof T]: T[R]} & { [P in K]: V[P] }
}[keyof V]
And lastly:
type Full = Combined<Base, {property1: number, property2: number}>
This type has the structure I expect it to have, yet, I can do something like this:
const X: Full = {
mandatoryProperty: 3,
property1: 2,
property2: 4
}
I only want either property1 or property2 to be within the type. Not both. If I understand correctly, this occurs because of typescript's excess property checking behaviour. How can I force it to not occur?
EDIT:
As @jcalz mentioned, one way to achieve the desired behaviour is to set unwanted properties to never. I try doing so by changing the type to:
type Combined<T, V> = {
[K in keyof V]: {[R in keyof T]: T[R]} & { [S in keyof V]: S extends K ? V[K] : never }
}[keyof V];
But this doesn't work. What is the reason?