I encountered this issue:
buyTicketData?.pricingOptions
resulting in this error message:
[tsl] ERROR in /Applications/MAMP/htdocs/wp-content/plugins/tikex/tikexModule/components/BuyTicket/PricingOptionInvoiceItemsFormFieldsCheckboxes.tsx(280,25)
TS2532: Object is possibly 'undefined'.
I'm puzzled as to why the left side of ?
being undefined causes an error when it is wrapped with ?
.
The types involved are as follows:
buyTicketData?: BuyTicketData;
export type BuyTicketData = {
pricingOptions?: PricingOptions;
}
export type PricingOptions = {
[optionId: string]: PricingOptionType;
};
export type PricingOptionType = {
invoiceItems?: InvoiceItems;
};
export type InvoiceItems = {
[invoiceItemId: string]: InvoiceItemData;
};
export type InvoiceItemData = {
defaultValue?: number;
};
This is the complete expression under consideration
<select
value={
startPaymentIn?.invoiceItems?.[key] != undefined
? startPaymentIn?.invoiceItems?.[key] == 1
? "Yes"
: "No"
: startPaymentIn?.pricingOptionId &&
buyTicketData?.pricingOptions?.[ // <-- here
startPaymentIn!.pricingOptionId!
].invoiceItems[key]?.defaultValue != undefined
? startPaymentIn?.pricingOptionId &&
buyTicketData?.pricingOptions?.[
startPaymentIn!.pricingOptionId!
].invoiceItems[key]?.defaultValue == 1
? "Yes"
: "No"
: undefined
}
Let's address this problem:
value={
startPaymentIn?.invoiceItems?.[key] != undefined
? startPaymentIn?.invoiceItems?.[key] == 1
? "Yes"
: "No"
: buyTicketData?.pricingOptions?.[
startPaymentIn?.pricingOptionId ?? ""
]?.invoiceItems?.[key]?.defaultValue != undefined
? buyTicketData?.pricingOptions?.[
startPaymentIn?.pricingOptionId ?? ""
]?.invoiceItems?.[key]?.defaultValue == 1
? "Yes"
: "No"
: undefined
}
I am unsure why this somewhat messy ?? ""
condition is necessary.