I know that there are similar questions here but mine is a little different.
There is an Interface that can have one or another property, let's call them black and white they aren't mandatory, so the Interface is valid without them and it is valid with one of them.
Good:
interface MyInterface {
name: string;
}
Good:
interface MyInterface {
name: string;
black?: boolean;
}
Good:
interface MyInterface {
name: string;
white?: boolean;
}
Bad: (or it could be Good if we can check that maximum one of either black or white is there)
interface MyInterface {
name: string;
black?: boolean;
white?: boolean;
}
Because TypeScript is structurally-typed, it is not an error for an object to have excess properties, unless you explicitly disallow this by setting the property's optional type to never, like this:
type BlackOptional = {
black?: boolean;
white?: never;
};
type WhiteOptional = {
black?: never;
white?: boolean;
};
type Name = {
name: string;
}
type Example = (Name & BlackOptional) | (Name & WhiteOptional);
const example1: Example = { /*
^^^^^^^^
Types of property 'black' are incompatible. Type 'boolean' is not assignable to type 'never'.(2322) */
name: 'name',
black: true,
white: true,
};
const example2: Example = {
name: 'name',
black: true,
};
const example3: Example = {
name: 'name',
white: true,
};