Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

Check with TS that both optional params either passed or undefined

$
0
0

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:

  1. Without using TS just simply check my condition with if somewhere before return
  2. 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={() => {}}/>

Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>