Infer type of react prop by sibling prop value

Viewed 72

I've defined two different Shop type:

interface BasicShop {
  address: string;
  distance?: number | null;
  name: string;
  thumbnail?: string;
}
interface FullShop {
  address: string;
  categories: string[];
  distance?: number | null;
  keywords: string[];
  lat: number;
  lng: number;
  name: string;
  rating: number;
  reviews: number;
  thumbnail?: string;
}

FullShop has more fields than BasicShop.

I'm trying to define a react component ShopListItem, which has its prop types like:

type PropType = {
    size: 'sm' | 'md',
    shop: BasicShop | FullShop
}

I want the type of shop can be determined by the value of size. For example, if size=sm, than shop=BasicShop and size=md than shop=FullShop. So that I can write the following code without type error:

<ShopListItem size='sm' shop={(object of type BasicShop)} />
<ShopListItem size='md' shop={(object of type FullShop)} />

How can I achevie this behavior?

1 Answers

Use union types for the whole definition instead of for the fields within your "struct" and you'll get a discriminate union (or ADT):

type PropType =
    { size: 'sm', shop: BasicShop }
  | { size: 'md', shop: FullShop }
Related