TypeScript DefinitelyTyped

TypeScript tutorial

📦 TypeScript DefinitelyTyped (@types)

In TypeScript DefinitelyTyped is a community-maintained repository that provides TypeScript type definitions for JavaScript libraries that are not written in TypeScript.

👉 These type definitions are published on npm under the @types scope.


🔍 Why DefinitelyTyped is Need

Many popular JavaScript libraries (like jQuery, Lodash, Express) were originally written in plain JavaScript, so they don’t include TypeScript types.

Without types ❌:

  • No auto-completion

  • No type checking

  • More runtime errors

With DefinitelyTyped ✅:

  • Full IntelliSense

  • Compile-time safety

  • Better developer experience


🧠 What are Type Definitions?

Type definitions describe:

  • Functions

  • Objects

  • Parameters

  • Return types

They usually come in .d.ts files.

Example:

declare function $(selector: string): any;

📥 Installing Type Definitions

Use npm to install types.

Example: jQuery

npm install jquery
npm install --save-dev @types/jquery

Now TypeScript understands jQuery:

$("#btn").hide();

📦 Common @types Packages

Library Types Package
Express @types/express
Node.js @types/node
React @types/react
Lodash @types/lodash
jQuery @types/jquery

⚙️ How TypeScript Finds @types

TypeScript automatically looks in:

node_modules/@types

You don’t need to import them manually in most cases.


🧪 Example with Express

npm install express
npm install --save-dev @types/express

import express from "express";

const app = express();

app.get(“/”, (req, res) => {
res.send(“Hello TypeScript”);
});

req and res are now fully typed


🔧 When You DON’T Need DefinitelyTyped

You don’t need @types if:

  • The library writes in TypeScript

  • The library includes its own .d.ts files

Example:

npm install axios

Axios already includes types ✅


📝 Custom Type Declarations

If no @types package exists, you can write your own.

// custom.d.ts
declare module "my-lib";

🔑 DefinitelyTyped Summary

Concept Meaning
DefinitelyTyped Repo of type definitions
@types/* npm packages for types
.d.ts Type declaration files
Benefit Type safety for JS libs

⭐ Best Practices

✔ Always install @types for JS libraries
✔ Add types as devDependencies
✔ Avoid any by using proper typings
✔ Write custom .d.ts if needed

You may also like...