I'm a little new to typescript and getting this error. Here is how I've defined a type:
type QtyComponentProps = {
loading: boolean;
itemQuantity: number;
itemPrice: number | string;
} & (
| {
isWarrantyItem: true;
product: WarrantyProps;
}
| {
isWarrantyItem: false;
product: SearchOffers;
}
);
I am getting error when I am rendering the component with isWarranty
:
<RenderQtyComponent
product={product}
loading={loading}
itemPrice={itemPrice}
itemQuantity={itemQuantity}
isWarrantyItem={isWarrantyItem}
/>
CodePudding user response:
You have defined types as true
| false
.
I believe you have made this:
const isWarrantyItem = false
It's inferring
the type as boolean
instead of true
| false
A few possible solutions.
- Directly pass
<RenderQtyComponent isWarrantyItem={false}/>
- Make the type explicit. Such as:
const isWarrantyItem: false = false
return <RenderQtyComponent isWarrantyItem={isWarrantyItem}/>
- Type casting -
<RenderQtyComponent isWarrantyItem={isWarrantyItem as false}/>
CodePudding user response:
I would suggest using conditional types https://www.typescriptlang.org/docs/handbook/2/conditional-types.html
Here is an example of how you would achieve this with the code you provided:
type QtyComponentProps<TWarrantyItem = boolean> = TWarrantyItem extends true
? {
loading: boolean;
itemQuantity: number;
itemPrice: number | string;
isWarrantyItem: TWarrantyItem;
product: WarrantyProps;
}
: {
loading: boolean;
itemQuantity: number;
itemPrice: number | string;
isWarrantyItem: TWarrantyItem;
product: SearchOffers;
};