In modern web development, we typically also work with third party libraries. We don't write all the code of our projects on our own. Instead, typically we utilize third party libraries so that we don't always have to reinvent the wheel on our own but can add certain functionalities to our projects and then just focus on our core business logic.

Here, we will learn about:

Screenshot 2022-12-14 at 10.32.00 AM.png

Using JavaScript (!) Libraries with TypeScript

First we will learn about lodash. Now, lodash is a JS libraries and we don’t need TS to use it, it can be used in normal JS also. Install it using:

npm i --save lodash

In the very basic project setup I tried to do this and use the suffle method of lodash.

Screenshot 2022-12-14 at 10.40.54 AM.png

But it is not working. This is the error:

Screenshot 2022-12-14 at 10.41.57 AM.png

Now, the problem is that lodash is a simple JS library. It is built using simple vanilla JS and its build for JS. Now, if I ignore the error using the tsconfig.json and try to run it. It will give an output. So, this proves that lodash works. It is just that TS dosen’t understand it. The problem is that there is no TS version of lodash and we have to live with it. These types of problems come sometimes in 3rd party libraries.

To solve this issue we will use the types package. It is this use package which contains many 3rd party libraries like lodash translated to TS. On npm: https://www.npmjs.com/package/@types/lodash

The github repo: https://github.com/DefinitelyTyped/DefinitelyTyped

This is the DefinitelyTyped repo with many 3rd party libraries translated to TS. Now, lets use the lodash one using:

npm install --save @types/lodash

Screenshot 2022-12-14 at 10.51.11 AM.png

Now, you can see that the error is gone. Output:

Screenshot 2022-12-14 at 10.52.29 AM.png

Using “declare” as a “Last Resort”

Now, what do you do when there is a library which do not have a types library already made. Or what if we have in our index.html: