Home > Back-end >  Typescript type 'boolean' is not assignable to 'false' error
Typescript type 'boolean' is not assignable to 'false' error

Time:10-14

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.

  1. Directly pass <RenderQtyComponent isWarrantyItem={false}/>
  2. Make the type explicit. Such as:
const isWarrantyItem: false = false

return <RenderQtyComponent isWarrantyItem={isWarrantyItem}/>
  1. 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;
    };
  • Related