I'm writing an app with React native and Typescript and I have a question.
Let's image we have a simple component with three properties, one required and two optional:
interface Props { requiredProp: string; optionalPropA: boolean; optionalPropB: Function;}
In my app logic either both optional properties have to be passed or none of them and I'm wondering how can I check that with TS?
I can think of only two ways how I can achieve that:
- Without using TS just simply check my condition with
if
somewhere beforereturn
- Combine two optional properties into one. Make an object with two keys (one for each property) and make a TS type that will make sure that either both or none of them exists
Some examples:
// Should be good because all params were passed<SimpleComponent requiredProp={'Hello world'} optionalPropA={true} optionalPropB={() => {}}/>
// Should be good because only required param was passed<SimpleComponent requiredProp={'Hello world'}/>
// Should complain that optionalPropB wasn't passed<SimpleComponent requiredProp={'Hello world'} optionalPropA={true}/>
// Should complain that optionalPropA wasn't passed<SimpleComponent requiredProp={'Hello world'} optionalPropB={() => {}}/>