Way to use 3rd party libraries in TypeScript
TypeScript is a superset of JavaScript and is used in most of the projects.
Unlike JavaScript, when we want to use some built-in package or libraries typescript fails to understand it.
Let take an example to understand it clearly. Lodash is one of the famous JS library which provides utility functions for daily use.
STEP1: Installation of lodash
npm install –save lodash
STEP2: Using lodash like regular JavaScript importing. shuffle function used below shuffles the data in array on load.
TypeScript is not happy with it and complaining about the package.
This is because those package was meant to be used with vanilla JS. TypeScript does not understand it.
Solution:
A. With most JS packages:
There is a package called DefinitelyTyped (i.e. @types).
It has list of many popular packages which is used in JavaScript. Refer below link:
Installing the package will do the trick. Now path will be handled and error will be gone
npm install --save @types/lodash
→ We now also have the auto completion of lodash package. Thanks to @types/lodash
B. MOST PLUGIN WILL BE THERE IN @types BUT NOT ALL:
→ If some JS code is written in any file or some plugin which is not there in @types package. There is a way to fix it.
→ TypeScript will not allow the use it
Eg.
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Project Manager</title> <link rel="stylesheet" href="app.css" /> <script type="module" src="dist/bundle.js"></script> </head> <body> <div id="app"></div> </body><!-- Use below data in another js file of the app --><script> const GLOBAL = "THIS IS SET";</script></html>
index.html
app.ts
→ To fix it we need to declare it’s type . We are certain these file exists, hence declaring right types
declare var GLOBAL: string; // Writing variable type
→ This was handled in @types plugin for most 3rd party libraries or packages.
C. Reviewing package: class-transformer
→ This package is helpful when we get lots of data from database or API and we need to convert the data to the instance of class
→ Let us see a code scenario
Case 1:
product.model.ts
export class Product { title:string; price:number; constructor(t:string, p:number) { this.title = t; this.price = p; } getInformation() { return [this.title, `$${this.price}`]; }}
app.ts
import { Product } from './product.model';const p1 = new Product('A Book', 12.99);console.log(p1.getInformation()); // this will give array of data
Case 2: Suppose now data is coming from database or some direct data is written. We need to make them in instance of class
app.ts
import { Product } from './product.model';// Assuming below data is loading from database or an APIlet products = [ {title: 'An Unbrella', price: 12.99},
{title: 'Rich Dad Poor Dad', price: 121.99},];// Making above data of class instance - custom codeconst loadedProducts = products.map(prod => {
return new Product(prod.title, prod.price);
});for(const prod of loadedProducts) {
console.log(prod.getInformation());
}
Everything is fine from above code. Wouldn’t it be nice if there is a package which can use instantiation for us.
Installation:
npm install class-transformer —- save
npm install reflect-metadata --save
app.ts
import 'reflect-metadata'; // must import from above packageimport { plainToClass } from 'class-transformer';import { Product } from './product.model';// Assuming below data is loading from database or APIlet products = [
{title: 'An Unbrella', price: 12.99},
{title: 'Rich Dad Poor Dad', price: 121.99},
];// Class Transformer: Param1 - className, Param2 - data
const loadedProducts = plainToClass(Product, products);// Previous way - custom code// const loadedProducts = products.map(prod => {
// return new Product(prod.title, prod.price);
// });for(const prod of loadedProducts) {
console.log(prod.getInformation());
}
→ The above o/p will be same as previous, lines of code is reduced, hence optimized.
Reference:
Summary:
Two ways two handle JS third party libraries in TypeScript:
a. Install specific package from @types or
b. adding types of the variables explicitly.
Closing thoughts:
As TypeScript can also use JavaScript libraries. Development becomes friendly.
Thank you for being till the end 🙌 . If you enjoyed this article or learned something new, support me by clicking the share button below to reach more people and/or give me a follow on Twitter to see some other tips, articles, and things I learn and share there.