0

I am working on a reusable component in React-Typescript. I need to validate my props OnClick and component as

  1. Both onClick and component prop are optional. I would pass these props to component only if I need them to be configured as such.
  2. Both of them shall not be passed to the component at the same time. ie, if I am passing in onClick then component prop shall not be passed in. Likewise if I am passing in component then onClick prop shall not be passed in.

I tried different combinations; This is the best possible scenario I reached;

interface Common {
   /** common items **/
} 
interface WithOnClick extends Common {
   onClick: () => void;
   component: never;
}
interface WithComponent extends Common {
   onCick: never;
   component: React.ReactElement<HTMLElement>
}
interface Main = WithComponent | WithOnClick | Common;

But this was still causing issues cause It was always resolving to Common;

Is there any possible way to define type for my scenario. Or am I doing something totaly wrong ?

Jake
  • 26
  • 4

1 Answers1

0

You could use a XOR type.

type XOR<T, U> = T | U extends object
  ?
      | ({ [P in Exclude<keyof T, keyof U>]?: never } & U)
      | ({ [P in Exclude<keyof U, keyof T>]?: never } & T)
  : T | U;

So your interfaces will become

interface WithOnClick extends Common {
   onClick: () => void;
}
interface WithComponent extends Common {
   component: React.ReactElement<HTMLElement>
}

Both onClick and component prop are optional.

You can play a bit with the type for this

Nullndr
  • 1,624
  • 1
  • 6
  • 24