I have the following component, which can either contain an image or a text. Hence in JSX I check whether there's an image (because that means there must not be text vice versa), and then either display the image or text.
How can I define this behavior with TypeScript types?
I BlockCtaDoubleData, which is always available, and EITHER BlockCtaDoubleImageData OR BlockCtaDoubleTextData.
I tried the following, but Typescript keeps throwing an error for props.text & props.image, but not for props.headline.
How so?
interface BlockCtaDoubleData
{
headline: string;
}
interface BlockCtaDoubleImageData extends BlockCtaDoubleData
{
image: string;
alt: string;
}
interface BlockCtaDoubleTextData extends BlockCtaDoubleData
{
text: string;
}
export type BlockCtaDoubleProps = BlockCtaDoubleTextData | BlockCtaDoubleImageData;
export function BlockCtaDouble(props: BlockCtaDoubleProps)
{
return (
<div>
{props.headline}
{props.image ? (
<img src={props.image} alt={props.alt}/>
) : (
{props.text}
)}
</div>
);
}
FYI: The error is saying that the respective prop is not existing in the counter type.