0
0
Typescriptprogramming~5 mins

DefinitelyTyped and @types packages in Typescript

Choose your learning style9 modes available
Introduction

Sometimes TypeScript needs extra information about JavaScript libraries to understand how to use them safely. DefinitelyTyped and @types packages give TypeScript this information.

You want to use a JavaScript library in your TypeScript project and need type information.
You want your code editor to show helpful hints and catch mistakes when using external libraries.
You want to avoid writing type definitions yourself for popular libraries.
You want to share type definitions with others easily.
You want to keep your project organized by installing types separately.
Syntax
Typescript
npm install --save-dev @types/library-name

The @types packages contain type definitions for JavaScript libraries.

They are usually installed as development dependencies because they help during coding but are not needed at runtime.

Examples
This installs type definitions for the popular lodash library.
Typescript
npm install --save-dev @types/lodash
This installs type definitions for the react library, so TypeScript understands React code.
Typescript
npm install --save-dev @types/react
This installs type definitions for Node.js built-in modules, useful when writing server-side TypeScript.
Typescript
npm install --save-dev @types/node
Sample Program

This program uses the lodash library to double numbers in an array. Installing @types/lodash helps TypeScript understand the _.map function and check types.

Typescript
import _ from 'lodash';

const numbers: number[] = [1, 2, 3, 4];
const doubled = _.map(numbers, n => n * 2);
console.log(doubled);
OutputSuccess
Important Notes

DefinitelyTyped is a big collection of type definitions maintained by the community.

When you install @types/library-name, you get the types from DefinitelyTyped for that library.

If a library already includes its own types, you don't need to install @types separately.

Summary

DefinitelyTyped provides type definitions for many JavaScript libraries.

@types packages let you add these types to your TypeScript projects easily.

Using them helps TypeScript check your code and gives better editor support.