Finding Declarations
When a third-party module that we are consuming does not have type declarations included, the TS compiler will throw an error like “Could not find a declaration file for module ‘module-name’”.
First check if there is a corresponding @types module. You can either simply try installing the module (e.g. pnpm add @types/foobar -D to get types for the foobar mdoule), or use TypeSearch to find it.
If there is no @types module, add a .d.ts file to the types folder with declare module 'module-name'. You can also add the interfaces, functions, constants, etc that you are using, with the appropriate types, so that our code is type-checked. Note: This is only a short-term solution. See the next section “Writing Declaration Files”.
Writing Declaration Files
In the long term, type declarations should be part of the original module or included in DefinitelyTyped (DT), so that others can use and help maintain them, and to keep those concerns separate.
The .d.ts file can serve as the basis for the declaration file that we contribute back to the community.
The best solution is to have the declarations included in the original module. However, not all module authors want to include or maintain these. A good start is to create an issue in module’s issue tracker asking about this, or submitting a PR with the declarations.
If the original module author declines or does not respond, the declarations can be added to the DT repository. Their README has good instructions on contributing. Banno already has a fork of DT for building and testing PRs.
Reading
- See this overview/tutorial on writing declaration files.
- DT has a guide on creating a declaration file along with best practices.
- TS has a section on writing declarations files with super-useful templates for the various types of modules.