3rd Party Libraries and TypeScript: A Beginner's Guide

Profile picture of Bhavik Bamania
Bhavik Bamania
·4 min read
3rd Party Libraries and TypeScript: A Beginner's Guide
3rd Party Libraries and TypeScript: A Beginner's Guide

As a developer, you'll often need to work with third-party libraries in your projects. These libraries provide pre-written, reusable code that can help you avoid reinventing the wheel. TypeScript adds static typing to these libraries, ensuring that you catch bugs early. In this post, we’ll explore how to use third-party libraries with TypeScript effectively.

Before You Proceed

If you're just getting started with TypeScript, you might want to check out some key concepts before diving into third-party libraries. Here's a list of beginner-friendly TypeScript guides that will help you build a solid foundation:

Working with Lodash in TypeScript

Lodash is a popular utility library that makes working with arrays, numbers, objects, and strings easier in JavaScript. But what happens when you want to use Lodash in TypeScript?

Luckily, Lodash provides its own type definitions, so you can use it seamlessly with TypeScript. Here’s how you can integrate Lodash into your TypeScript project.

Step 1: Install Lodash and Its Type Definitions

npm install lodash
npm install @types/lodash --save-dev
  • lodash: The core Lodash library.
  • @types/lodash: Type definitions that allow TypeScript to understand Lodash’s methods and their types.

Step 2: Import and Use Lodash in TypeScript

Now, let’s use a simple example to see how Lodash works in TypeScript:

import _ from 'lodash';

const numbers: number[] = [1, 2, 3, 4, 5];
const shuffled = _.shuffle(numbers); // The _.shuffle method randomizes the order of the array

console.log(shuffled); // [3, 1, 5, 4, 2] (the result may vary)

What Makes Lodash Great in TypeScript?

Thanks to its type definitions, Lodash methods like _.shuffle come with autocomplete and type safety. TypeScript will warn you if you try to pass the wrong data type to a Lodash method, reducing the chance of bugs in your code.

What to Do When You Can't Install the Types Package?

Sometimes, you may encounter a third-party library that doesn’t provide built-in TypeScript support. Or, the type definitions you need aren’t available. In such cases, you can use TypeScript’s declare keyword to work around this issue.

Using declare

When you don’t have a type package available for a library, you can declare the types yourself. For example, let’s say you’re using a fictional library called mylib, but there are no type definitions available.

// Declare the module in a .d.ts file
declare module 'mylib' {
  export function doSomething(arg: string): string;
}

// Then, use it in your code
import { doSomething } from 'mylib';

const result = doSomething('Hello TypeScript');
console.log(result);

By using declare, we’re telling TypeScript, “Hey, I know this library exists, and I know what functions and types it provides, even if there’s no official type definition.”

Common Use Case for declare

  • Using older or lesser-known libraries that don’t have official types.
  • Temporarily using declare until the library’s type definitions are published.

No Types Needed: Working with class-transformer

Some libraries are TypeScript-friendly by design, meaning you don’t need to install any type definitions or use workarounds. One such library is class-transformer.

Class-transformer helps convert plain JavaScript objects into instances of classes, allowing you to validate and manipulate them with ease. Here’s a basic example:

import 'reflect-metadata';
import { plainToClass } from 'class-transformer';

class User {
  name: string;
  age: number;
}

const plainUser = { name: 'John', age: 25 };
const user = plainToClass(User, plainUser);

console.log(user instanceof User); // true

Why is class-transformer TypeScript-friendly?

  • It’s built with TypeScript in mind, so you don’t need to install any additional type definitions.
  • It leverages TypeScript’s decorators, making it a great fit for TypeScript projects.

TypeScript-Embracing Libraries: class-validator

Some libraries take TypeScript support to the next level by fully embracing its capabilities. class-validator is a library that allows you to add validation rules to your classes using TypeScript decorators.

Example: Validating a User Object

import { IsEmail, IsNotEmpty, validate } from 'class-validator';

class User {
  @IsNotEmpty()
  name: string;

  @IsEmail()
  email: string;
}

const user = new User();
user.name = '';
user.email = 'invalid-email';

validate(user).then(errors => {
  if (errors.length > 0) {
    console.log('Validation failed: ', errors);
  } else {
    console.log('Validation passed!');
  }
});

Why is class-validator Great for TypeScript?

  • It uses TypeScript decorators to apply validation rules directly to class properties.
  • TypeScript’s strong typing helps catch potential issues early, reducing runtime errors.
  • Perfect for projects that require strict input validation (e.g., form submissions).

Conclusion

TypeScript makes working with third-party libraries a smooth experience by providing type definitions and tools like ts-loader and declare. Whether you're working with libraries that are type-friendly (like class-transformer) or require a bit of manual work (like Lodash without types), TypeScript helps ensure your code remains reliable and bug-free.

For more advanced use cases, libraries like class-validator are excellent tools that embrace TypeScript’s capabilities, allowing you to write safer, more maintainable code.

Author of Bhavik Bamania

Written by

Bhavik Bamania