gpt4 book ai didi

javascript - 为什么我在这个可选链中收到 "Object is possibly ' undefined'"?

转载 作者:行者123 更新时间:2023-12-02 01:48:17 24 4
gpt4 key购买 nike

我到达这里:

buyTicketData?.pricingOptions

这个错误:

[tsl] ERROR in /Applications/MAMP/htdocs/wp-content/plugins/tikex/tikexModule/components/BuyTicket/PricingOptionInvoiceItemsFormFieldsCheckboxes.tsx(280,25)
TS2532: Object is possibly 'undefined'.

如果 ? 的左侧未定义,为什么 ? 会包裹它,而不是?

以下是类型:

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;
};

这就是整个表达式

<select
value={
startPaymentIn?.invoiceItems?.[key] != undefined
? startPaymentIn?.invoiceItems?.[key] == 1
? "Igen"
: "Nem"
: startPaymentIn?.pricingOptionId &&
buyTicketData?.pricingOptions?.[ // <-- here
startPaymentIn!.pricingOptionId!
].invoiceItems[key]?.defaultValue != undefined
? startPaymentIn?.pricingOptionId &&
buyTicketData?.pricingOptions?.[
startPaymentIn!.pricingOptionId!
].invoiceItems[key]?.defaultValue == 1
? "Igen"
: "Nem"
: undefined
}

好的,找到解决方案:

value={
startPaymentIn?.invoiceItems?.[key] != undefined
? startPaymentIn?.invoiceItems?.[key] == 1
? "Igen"
: "Nem"
: buyTicketData?.pricingOptions?.[
startPaymentIn?.pricingOptionId ?? ""
]?.invoiceItems?.[key]?.defaultValue != undefined
? buyTicketData?.pricingOptions?.[
startPaymentIn?.pricingOptionId ?? ""
]?.invoiceItems?.[key]?.defaultValue == 1
? "Igen"
: "Nem"
: undefined
}

我只是不知道为什么这个丑陋的? ""条件需要。

最佳答案

如果 aundefined,则 a.b 会抛出异常,而 a?.b 则解析为 undefined 。您仍然需要处理未定义

buyTicketData?.pricingOptions?.[startPaymentIn?.pricingOptionId]

决定

buyTicketData?.pricingOptions?.[undefined]

如果startPaymentIn未定义。这会引发错误,因为 undefined 不能是键。

如果这个变量是必需的,更好的方法是在所有内容之前进行空检查,这样您就根本不需要?.

if(startPaymentIn)
{
//no need to use ?. on startPayment
}

关于javascript - 为什么我在这个可选链中收到 "Object is possibly ' undefined'"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70647673/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com