PayPal’s type definitions are available for import together as part of the loadScript() method or individually using the import type functionality. The following post will highlight some of the features of the package and provide insight on how to, “make use of the type definitions to speed up the development of your PayPal applications.”
The package install is the same whether using the loadScript() or import type functionality.
npm install @paypal/paypal-js
Type Definitions with LoadScript
- The paypal-js module provides the loadScript() method.
- The loadScript() injects the SDK <script> tag onto the page.
- When the script tag is injected onto the page, a promise is returned.
- The promise resolves after the script is loaded successfully.
Tasks such as handing errors and reloading the script when parameters change (currency changes for example) are much easier using this utility.
The image below represents a basic usage example.
TypeScript type definitions outline what is expected for the input and what the expected return value will be. In the example above, this is seen in the drop-down menu’s highlighted option for the create order button. Just beside it there is a second menu showing exactly what is expected inside of the create order button.
The IDE will notate an error if anything is missing or typed in incorrectly.
Hovering over the text will provide detailed information about missing arguments and hitting cmd-click on the createOrder method will bring the developer directly to the TypeScript definition.
Opting in to Additional Functionality
TypeScript Definitions without LoadScript
The loadScript() method isn’t required to enable TypeScript definitions in a user’s application. Using the import type syntax rather than the more common import syntax will bypass bringing the dependency into an application and grant access to the benefits of TypeScript at build-time without adding to the bundle size.
Import and import type from the paypal-js module both provide access to the type definitions for the loadScript module and the global window.paypal variable as well.
In the example above, both the myIntent and postal_code properties are mistyped prompting a similar error to the one in the image below. This illustrates similarities between type definition functionalities when using the import and import type syntax.
There are dozens of PayPal-related types, each with their own extensive documentation about their properties and purpose, available for use in applications.