Setting up a Project with Express and TypeScript

Bare minimum Typescript Setup
first make a folder and
npi initrun
tsc --initchange root directory on
tsconfig.jsonfile :
"rootDir": "./src",
"outDir": "./dist",(/dist = distributable file)
to compile
tsc -p .YOU NEED TO DO IT EVERY time you make some changes to your codeto run
node /dist/filename.jsmake .gitignore file and add ( dist/, node_modules/ , .env)
and runnpx gitignore Nodeeven if you have typscript installed on your machine globally, it is good idea to instal typescript in your project too. (Better install as dev dependency)
npm i typescript -Dto get rid of problem described in number 4 .. install
npm i tsc-watch -D
and
set up a script dev as following:"dev": " tsc-watch --onSuccess \"node dist/index.js\""you can change
"type": "module", //commonjs---> module
Installing Express and Its Type Definitions in TypeScript
After setting up your TypeScript , you usually install Express like this:
npm install express
But here’s the catch: if you try to use Express in your .ts files immediately, TypeScript will complain:
Cannot find module 'express' or its corresponding type declarations.
This happens because Express is written in plain JavaScript, so TypeScript can’t automatically know the types of its functions, objects, or middleware.
There are two ways to fix this:
Write your own types – You can create type definitions (
.d.ts) for the functions, objects, or methods you plan to use in Express. But this can be tedious.Install existing type definitions – The easier way is to use the community-maintained types from npm. Packages with the
@types/prefix are exactly for this.
npm i @types/express -D
Here’s what happens when you run this:
TypeScript now knows the structure of Express, including functions, request/response objects, and middleware.
Your editor (like VS Code) will give you autocomplete, hints, and error checking for Express code. any previous “Cannot find module” errors will disappear.
Pro tip: On the npm website, look at the top-right corner of the package name. If you see DT or ts, it means this package includes TypeScript type definitions.
DT → comes from DefinitelyTyped, the community-maintained repository of type definitions.
ts → the package itself is written in TypeScript or includes its own types.
This is a quick way to check if a JavaScript library is TypeScript-ready before installing it.
Node.js Type Definitions in TypeScript
TypeScript doesn’t know the types of Node’s built-in modules (fs, http, path, etc.) by default. To fix this, install the Node type definitions:
npm i -D @types/node
This lets TypeScript understand Node modules and provides autocomplete, hints, and error checking in your editor.



