Sometimes you want to have compile safety for your
React component that can have either properties of
type X
or of type Y
but not both.
Intuitively I would have thought that you can use union types for that such as
type Props = PropsA | PropsB;
but it turns out this is not the case.
The correct solution to this problem is
export type XOR<T, U> = (T | U) extends object ? (T & { [K in keyof U]?: never }) | (U & { [K in keyof T]?: never }) : T | U;
interface PropsA { text1: string}interface PropsB { text2: string}
type Props = XOR<PropsA, PropsB>;
const MyComp: React.FC<Props> = (props) => { return <div>{JSON.stringify(props, null,2)}</div>}
So when we now use this component with both props, we get an error
The valid variations are <MyComp text1="foo" />
or <MyComp text2="foo" />
but not both.