DEV Community

Avishka Guruge
Avishka Guruge

Posted on

Using JavaScript Packages without TypeScript Declarations in TypeScript

Let's assume you want to install and use a third-party package in your TypeScript project. When you try to import it into a file, you might encounter a ts(7016) error.

ts(7016) error

Try installing its type declaration.

npm i --save-dev @types/react-native-scroll-indicator
Enter fullscreen mode Exit fullscreen mode

Even attempting to install @types/react-native-scroll-indicator might result in a failure with a Not found error.

This means that the package does not include its own Typescript definitions.

But, TypeScript needs to know the types of the functions and variables in the package to ensure type safety.

No need to worry! You can still incorporate this package into your project. Here's how.

There are a few ways you can address this issue.


Method 1: Write your own type definitions

write a .d.ts file for the library in your project's working copy, as below.

declare module 'some-library' {
  export const doInterestingThings(): void;
}
Enter fullscreen mode Exit fullscreen mode

However, it's worth noting that the definitions could be extensive.

Therefore, this approach is not recommended, given its potential for being time-consuming and error-prone.


Method 2: Generate type definitions with dts-gen tool

dts-gen is a tool that generates TypeScript definition files (.d.ts) from any JavaScript object.

It's incredibly simple!

You'll need to first install dts-gen if you haven't already:

npm install -g dts-gen
Enter fullscreen mode Exit fullscreen mode

Navigate to your project directory. Now, Install your package if you haven't already installed.

Run the following command to generate the type definitions for the some-library package:

dts-gen -m some-library
Enter fullscreen mode Exit fullscreen mode

This will generate a file named some-library.d.ts in your project directory with the type definitions for the some-library package.

In most cases, this method works well, unless there's an error in the JavaScript files.


In such a scenario, you can do the following:

write a .d.ts file for the library in your project's working copy, as below.

declare module 'some-library';
Enter fullscreen mode Exit fullscreen mode

Essentially, it informs TypeScript, "Hey, this thing exists; stop flagging errors, and let me use it as I see fit."

This means that you won’t get any type checking or autocompletion for those functions or variables.πŸ₯²


Hence, Method 2 is typically the recommended approach, as it offers more comprehensive type information and helps minimize the risk of errors.

I hope this helps! Let me know if you have any other questions.

Good luck!

Top comments (0)