Cannot find a way to do conditional props

  Kiến thức lập trình

I currently have two components:

export interface MediaCardProps {
  alt: string;
  src: string;
}

export const MediaCard = ({ alt, src }: MediaCardProps) => {
  ...
};

and

export interface TextCardProps {
  isLoaded: boolean;
  children: ReactNode;
}

export const TextCard = ({ children, isLoaded = false }: TextCardProps) => {
   ...
};

I would like to create a parent component like this:

type Props = ({ isMedia: false } & TextCardProps) | ({ isMedia: true } & MediaCardProps);

export const Card = ({ isMedia = false, ...args }: Props) => {
  if (isMedia) return <MediaCard {...(args as MediaCardProps)} />;

  return <TextCard {...(args as TextCardProps)} />;
};

The goal here is that when isMedia is set to true, we only see the MediaCardProps, otherwise, we see the TextCardProps.

But doing so, I have an issue when calling it.
I call it this way:

<Card isLoaded={!!data.title}>
  <h1 className='text-2xl font-bold'>{data.title}</h1>
</Card>

and I have this error Type '{ children: Element; isLoaded: boolean; }' is not assignable to type 'IntrinsicAttributes & Props'. Property 'isMedia' is missing in type '{ children: Element; isLoaded: boolean; }' but required in type '{ isMedia: false; }'.

I managed to fix it by changing my parent Props to this:

type Props = { isMedia?: false; args: TextCardProps } | { isMedia: true; args: MediaCardProps };

but I don’t want the args prop.

Many thanks if you can help me fix this !

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT