START EXPRESS JS WITH TYPESCRIPT
Meet Vaghasiya
Passionate Vue.js & Laravel Developer | JavaScript Lover | Eager to Learn
In this article, we will learn
How to install express js with typescript
Start with creating a new directory. so run the below command
mkdir typescript-node
cd typscript-node
npm i express
npm i nodemon concurrently -D
npm init --yes
tsc init
Let's make scripts to compile our typescript code into javascript and also run on all changes. so before that, we need to create a src folder and create an index.ts file. then also make a build folder and make an index.js file in that.
run npm run start. if hello world will print in the terminal.
Configure tsconfig.json file.
We have to add rootDir to src/index.ts and outDir to build. let's understand all options one by one.
Typescript definitions file
We install many dependencies in the our project and not all packages are written in typescript. so to work with that code, we need to install a definitions files for a particular library. These files are declarations without implementations. These files have d.ts extensions.
npm i typscript @types/express @types/node -D
Here @types/express and @types/node is definitions file for express and node.
Create a server on express
if you forgot to install @types/express then it will show the below error. so kindly install express and node type definitions file.
import Request, and Response type from express. and make a server with a basic / router like below.
We will make multiple routes, so let's make a routers folder and create loginRoute file their. and paste this code from index.ts to routes/loginRoute.ts
领英推荐
so let's start now
npm i body-parser
2. import in index.ts.
3. make a login route file. for getting and posting both methods. Then check if when you click on the button, then you get the email and password on response or not.
4. Now here we have some problems. let's understand step by step
Here we have to make sure, that interface of the body is correct. because if data is not get from the request, then the typescript will give an error in runtime. so we have to be sure about the key and value type of the object in the interface and from request should be the same. this thing we can not avoid.
5. Now install cookie-session and @types/cookie-session.
this type of package will add a session key to our request object. otherwise, the typescript will give us an error.
6. create / and /logout router. so when users successfully login then we can redirect them to / and when they want log out then we can remove the session cookie from the req object.
7. let's make a protected route and practice middleware. in middleware, we have to use NextFunction type for middleware next function like,
That's it, guys...I hope now you can use express js with typescript. and able to modify some requestBody, create multiple routes, use a different package like body-parser and cookie-session, and understood why types of file are required, of other modules,