我在 SvelteKit 应用程序中使用 PayPal SDK,使用 TypeScript。我遇到了这样的问题:像记录的那样运行他们的
paypal.Buttons
方法总是会导致 TypeScript 错误。
例如,这是他们的 README 中的代码:
import { loadScript } from "@paypal/paypal-js";
let paypal;
try {
paypal = await loadScript({ clientId: "test" });
} catch (error) {
console.error("failed to load the PayPal JS SDK script", error);
}
if (paypal) {
try {
await paypal.Buttons().render("#your-container-element");
} catch (error) {
console.error("failed to render the PayPal Buttons", error);
}
}
但这会在第 13 行
Cannot invoke an object which is possibly undefined
上给出错误 paypal.Buttons()
。我怎样才能调用他们的方法而不让这个错误总是出现在我的 linter 输出中?我不知道他们的自述文件是否需要更新,或者他们的代码是否需要修复以返回更好的类型?
我认为他们的类型真的没有意义。
export interface PayPalNamespace {
Buttons?: (
options?: PayPalButtonsComponentOptions,
) => PayPalButtonsComponent;
Marks?: (options?: PayPalMarksComponentOptions) => PayPalMarksComponent;
Messages?: (
options?: PayPalMessagesComponentOptions,
) => PayPalMessagesComponent;
HostedFields?: PayPalHostedFieldsComponent;
getFundingSources?: getFundingSources;
isFundingEligible?: isFundingEligible;
rememberFunding?: rememberFunding;
FUNDING?: Record<string, FUNDING_SOURCE>;
version: string;
}
比如,为什么按钮是可选的?
但无论如何,找到了一个简单的解决方法来消除错误:
if (paypal && paypal.Buttons) {
try {
await paypal.Buttons().render("#your-container-element");
} catch (error) {
console.error("failed to render the PayPal Buttons", error);
}
}