Background
To tackle this issue, we must first delve into how TypeScript locates type definitions for a specific module. The mapping of type definitions to the module name is crucial in this process. There are two known methods to achieve this:
Using declare module
The d.ts
files can define the module name like so:
declare module 'stripe' {
// types
}
The filename and location of the file holding the module name declaration do not matter. What's important is that the module name is specified within the file using declare module
. However, TypeScript must still load the file for this to take effect.
Using the filename
Type definitions in @types
(including the official one from stripe) are resolved based on their filenames. When you import stripe
, TypeScript will search for a definitions file under node_modules/@types/stripe
and utilize it as the type for that module.
Solution
Let's analyze your problem in light of this information. It appears that the type definitions for stripe lack a declare module
statement. Consequently, simply loading the file will not suffice.
You have several approaches to resolve this situation:
1. Implement a path mapping
In your tsconfig.json
, incorporate the paths
and baseUrl
settings (baseUrl
is mandatory for paths
functionality):
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"stripe": ["./node_modules/@reggi/types-stripe"]
}
}
}
This configuration guides TypeScript to look for stripe
in an alternative location during resolution.
You can also make this more dynamic for multiple packages by incorporating a wildcard:
"paths": {
"*": ["./node_modules/@reggi/types/*", "*"]
}
Note that in this scenario, the types should be stored in a subfolder named stripe
, along with potential other package subfolders.
2. Introduce a declare module
Alternatively, you could adjust the index.d.ts
to include a declare module
statement. Essentially, you need to encapsulate the entire content of the file within it, as demonstrated below:
declare module 'stripe' {
class Stripe {
DEFAULT_HOST: string;
DEFAULT_PORT: string;
// ...
}
It's worth noting that TypeScript might raise concerns about the existing type definitions' two declare
keywords (declare class Stripe
and declare namespace Stripe
). These redundant declarations should be removed.
Finally, ensure that the d.ts
file is loaded. You can accomplish this easily by adding it to the include
option in your tsconfig.json
{
"compilerOptions": {
...
},
"include": [
"./node_modules/@reggi/types-stripe/index.d.ts"
]
}
Note: If preferred, there is no obligation to use an npm package. From TypeScript's perspective, the origin of the files is irrelevant as long as the paths are correctly specified in typeRoots
/ include
.