AI Hints
Home›TypeScript Tutorial›Configuration and Packages
TypeScript · Lesson 78 of 120

npm Packages and @types

Typed libraries.

⏱ 2 min read▶ Video at 1:00:49🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Most NPM packages ship their own types today. For older ones, the community writes types in separate packages, named at types, slash, the package name.

npm Packages and @types
From the video: npm Packages and @types
  • Packages with types
  • Or @types
  • Community types

Node's own types

Node's built in modules are typed by the at types slash node package. Read file sync and join are fully typed, including their options. Run it.

app.tstypescript
import { writeFileSync, readFileSync } from "node:fs";
import { join } from "node:path";

const file = join(".", "stock.json");
writeFileSync(file, JSON.stringify({ Leeds: 12, York: 5 }));

const text: string = readFileSync(file, "utf8");
console.log(file, "->", text);
Output
stock.json -> {"Leeds":12,"York":5}

Installing types

If a package has no types, install its at types package as a dev dependency. If neither exists, write a small declaration file yourself. And your editor will tell you which case you're in.

keyvalue
Built inmost packages
Missingnpm i -D @types/x
None at allwrite a .d.ts
Node@types/node

Summary

Most packages include types. For the rest, install at types, or write a declaration. Next, promises and async.

Key takeaways
  • @types/node
  • npm i -D @types/x
  • Or .d.ts
Next up: Promises and async — typed waiting