I saw this pattern of using React component to make conditionals and ternaries inlined in JSX a bit more readable. But, would love to hear if someone has any input to a TS related "problem" with using such an approach.
So, given I have my component <MyComponent />
it's defined so that it takes a prop foo
. This prop must be a string.
type Props = { foo: string};
const MyComponent: FC<Props> = ({ foo }) => ...
Then, I have a wrapper component to help me make som conditional statements a little easier to reason about (sometimes);
type Props = { condition: boolean};
const Conditional: FC<Props> = ({ condition, children }) => (condition ? <>{children}</> : null);
Now, example A works (ofc...) - but example B does not. Maybe someone knows exactly why, I might have some guesses but not that comfortable around React yet to out them ;) And of course even more interesting, maybe someone has an idea how to make example B work?
Example A;
{bar && <MyComponent foo={bar} />}
Example B;
<Conditional condition={bar!==undefined}>
<MyComponent foo={bar} />
</Conditional>
B gives the error; Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.ts(2322)