Blog Logo

02 Oct 2024 ~ 1 min read

Typescript XOR types for react components


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

alt text

The valid variations are <MyComp text1="foo" /> or <MyComp text2="foo" /> but not both.


Headshot of Rainer Burgstaller

Hi, I'm Rainer. I'm a software engineer based in Salzburg. You can follow me on Twitter, see some of my work on GitHub, or read more about me on my website.