'Typescript conditional type depending of a boolean within the same Type

I'm trying to make an attribute of a Type be A or B depending on a boolean of the same type. Something like this:

interface ICardsGridSection {
  title: string;
  isSmallCard?: boolean;
  data: ICardsGridSection['isSmallCard'] extends true ? ICard[] : IFullCard[];
}

This is to limit the type of data of the Cards' grid depending on which card is wanted to be rendered in the react component.

So if someone does

<CardsGrid isSmallCard data={[]}/>

data type would be ICard[]

But, if instead it's:

<CardsGrid data={[]}/>

data type would be IFullCard[]



Solution 1:[1]

Got it!

You need to create both type for each case. A bit too manual but it works

type TCardsGridSectionBase = {
  title: string;
  className?: string;
};

type TSmallCardsGrid = {
  isSmallCard?: true;
  data: ICard[];
};

type TCardsGrid = {
  isSmallCard?: false;
  data: IFullCard[];
};

type TCardsGridSection = TCardsGridSectionBase & (TSmallCardsGrid | TCardsGrid);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 LuisEgan