I was using such approach for passing a props conditionally (depending on another prop) in react:
type CommonProps = { age: number };
type ConditionalProps =
| {
type: 'view' | 'add';
}
| {
type: 'edit';
initialData: number;
};
let Test = (props: CommonProps & ConditionalProps) => {
return <div />;
};
My goal was:
- if
type
is passed as "view" or "add", then I want TS to error if I passinitialData
- if
type
is passed as "edit" theninitialData
should be required.
This actually worked most of the time, until value of type
was dynamic.
When I passed value of type
like this:
<Test
age={9}
type={Math.random() > 0.5 ? 'edit' : 'view'}
initialData={9}
/>
Now it seems there is bug above, because TS isn't complaining anymore, and it can happen that type
is "view" and I also pass initialData
, which violates my first goal above.
I am not sure maybe I am asking too much, but is there an approach which achieves my above two goals also when value of type
is dynamic like in this example?