Home > Blockchain >  TypeScript, why? "is not assignable to type"
TypeScript, why? "is not assignable to type"

Time:02-20

I have two variables with same type, copy is taken with spread operator, but TypeScript check does not accept it why?

const [startPaymentIn, setStartPaymentIn] = useState<
  StartPaymentIn | undefined
>(undefined);

let startPaymentIn2: StartPaymentIn | undefined = {
  ...startPaymentIn,
};

setStartPaymentIn(startPaymentIn2);

Error:

ERROR in /Applications/MAMP/htdocs/wp-content/plugins/tikex/tikexModule/components/BuyTicket/PricingOptionInvoiceItemsFormFieldsCheckboxes.tsx
./tikexModule/components/BuyTicket/PricingOptionInvoiceItemsFormFieldsCheckboxes.tsx 172:20-35
[tsl] ERROR in /Applications/MAMP/htdocs/wp-content/plugins/tikex/tikexModule/components/BuyTicket/PricingOptionInvoiceItemsFormFieldsCheckboxes.tsx(172,21)
      TS2322: Type '{ eventId?: string | undefined; quantity?: number | undefined; link?: string | undefined; partnerData?: NameAndAddress | undefined; passTypeId?: string | undefined; ... 17 more ...; deliveryData?: NameAndAddress | undefined; }' is not assignable to type 'StartPaymentIn'.
  Types of property 'eventId' are incompatible.
    Type 'string | undefined' is not assignable to type 'string'.
      Type 'undefined' is not assignable to type 'string'.
export type StartPaymentIn = {
  eventId: string;
  quantity?: number;
  link?: string;
  partnerData?: NameAndAddress;
  passTypeId?: string;
  eventTimesSelected?: EventTimesSelected;
...

CodePudding user response:

If startPaymentIn is undefined the result of { ...startPaymentIn } will be {} which is not compatible with StartPaymentIn | undefined.

What you can do is startPaymentIn && { ...startPaymentIn }

Playground

  • Related