I made a simple <If /> function component using React:
import React, { ReactElement } from "react";
interface Props {
condition: boolean;
comment?: any;
}
export function If(props: React.PropsWithChildren<Props>): ReactElement | null {
if (props.condition) {
return <>{props.children}</>;
}
return null;
}
It lets me write a cleaner code, such as:
render() {
...
<If condition={truthy}>
presnet if truthy
</If>
...
In most cases, it works good, But when I want to check for example if a given variable is not defined and then pass it as property, it becomes an issue. I'll give an example:
Let's say I have a component called <Animal /> which has the following Props:
interface AnimalProps {
animal: Animal;
}
and now I have another component which renders the following DOM:
const animal: Animal | undefined = ...;
return (
<If condition={animal !== undefined} comment="if animal is defined, then present it">
<Animal animal={animal} /> // <-- Error! expected Animal, but got Animal | undefined
</If>
);
As I commented, althought in fact animal is not defined, I've got no way of telling Typescript that I already checked it. Assertion of animal! would work, but that's not what I'm looking for.
Any ideas?