Integrating TypeScript with JS libraries
To integrate we can have three solutions.
Use a library normally, adding basic type annotations wherever possible.
Use a TypeScript adapter library that has helpers for using library with TypeScript
Change our JS library to work with TypeScript classes.
We are installing the types for the Express in our project. Let's see how we will change our JS code of Express to TS code. But before that let's set up our project
Project Setup
Make sure you are in the directory where your project is. Now follow these steps first before writing any new code
If not present in your project, create a package.json file using the command 'npm init -y'. Since your project is already using JS, you won't need this step.
Create ts config file. Write the following command in terminal and hit enter 'tsc --init' .
Install 'nodemon' and 'concurrently' after tsconfig.json file. Use the following command 'npm i concurrently nodemon'.
If you don't have src and build folder, make one in the root directory.
Inside the tsconfig.json file, uncomment outDir and rootDir keys.
Make outDir as ./build and rootDir as ./src
We want 'noImplicitAny' to true.
Set 'strictPropertyInitialization' to false, this setting if set true will force us to initialize all the classes which we don't want.
Uncomment 'noUnusedLocals' and 'noImplicitReturns'.Inside the package.json file, make sure to have these three scripts
"dev": "nodemon src/index.ts",
"build": "npx tsc",
"start": "node dist/index.js",
Now run npm start. It might through an error. Close the terminal and re-start again using npm start.
Move the existing code in the .src folder.
Re-name the file extensions from .js to .ts
Points to note :
Importing types of req and response
We will start by importing the types for Request and Reponse for our express code.
If you are wondering why we are using the Request and Response only, go to your code and control + click on 'express'. If you are on mac, use command + click
It will open a document with the extension index.d.ts. You will see a list of interfaces that express supports
* These are the exposed prototypes.
*/
var application: Application;
var request: Request;
var response: Response;
/**
Let's move to changing our JS code to TS code now.
In our call back function set the type of req and res to Request and Response
import express, {Request, Response} from 'express';
const app = express();
X app.get('/', (req: Request, res: Response) => {
res.send('Working');
})
See on line X what we did in our callback function.
EsLint and Prettier integration
Install ESLint
npm i eslint --save-dev
Now initiate the aslant config file
npx eslint --init
Remember our project runs on node, our config file is JSON while setting up.
Create a .prettierrc file
Create file named .prettierrc and add the following
{
"printWidth":60,
"tabWidth":2,
"singleQuote":true,
"trailingComma": "all",
"semi":true
}
Make sure eslant and prettier plugins are installed on vscode