DEV Community

Cover image for Custom Type Definitions for JavaScript dependencies
Ankur Sheel
Ankur Sheel

Posted on • Originally published at ankursheel.com on

Custom Type Definitions for JavaScript dependencies

If you are importing a javascript dependency into your typescript app, you might run into this error

“Could not find a declaration file for module ‘third-party-library-name’. ‘third-party-library-name.js’ has an ‘any’ type. Try npm install @types/third-party-library-name if it exists or add a new declaration (.d.ts) file containing declare module ‘third-party-library-name’;”

If you read the error message, you can see that it’s suggesting to check the DefinitelyTyped repository.

If you are lucky you will find it the repository and can install it using npm or yarn.

But what if you not so lucky?

Solution #1

Now, you will only see this error if you have noImplicitAny: true in your tsconfig.json. So you could get around this error is by setting noImplicitAny: false.

But, by doing this you lose type-safety, so let’s rule this out as a viable option.

Solution #2

Add a local declaration file.

Steps

So, how exactly do you do that?

  1. Create a types folder.
  2. Edit tsconfig.json to use the typeRoots property so that the compiler can find the local declaration files. You will need it to include both your local folder as well as node_modules/@types. You will also want to check the local folder before the node_modules folder.
"compilerOptions": {
 ...
 "typeRoots": ["./types", "node_modules/@types"]
    }
  1. Add the property to exclude property in tsconfig so that it does not get compiled.
"exclude": [..., "types"]
  1. Add a third-party-library-name folder in the types directory.
  2. Add an index.d.ts in that folder.
  3. Add your TypeDefinitions. But if like me, you want to prototype things or do not want to write a full custom type, you can declare the module by adding this to the index.d.ts file.
declare module 'third-party-library-name';

The only caveat is that you don’t get any IntelliSense.

Conclusion

Hopefully, this post will help you and you won’t have to resort to either removing Typescript from your project or losing type-safety by adding noImplicitAny: false in your tsconfig.json.

Top comments (0)