<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: AliFathy-1999</title>
    <description>The latest articles on DEV Community by AliFathy-1999 (@alifathy1999).</description>
    <link>https://dev.to/alifathy1999</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F705487%2F9aac27e9-ca7d-4cf2-8780-cbb217e70629.jpg</url>
      <title>DEV Community: AliFathy-1999</title>
      <link>https://dev.to/alifathy1999</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/alifathy1999"/>
    <language>en</language>
    <item>
      <title>How to Implement Data Validation in NestJS Using nestjs-joi and joi-class-decorators</title>
      <dc:creator>AliFathy-1999</dc:creator>
      <pubDate>Thu, 20 Jun 2024 18:14:08 +0000</pubDate>
      <link>https://dev.to/alifathy1999/how-to-implement-data-validation-in-nestjs-using-nestjs-joi-and-joi-class-decorators-1bk3</link>
      <guid>https://dev.to/alifathy1999/how-to-implement-data-validation-in-nestjs-using-nestjs-joi-and-joi-class-decorators-1bk3</guid>
      <description>&lt;h2&gt;
  
  
  Here are some topics I can cover:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Introduction to Data Validation in Web Applications.&lt;/li&gt;
&lt;li&gt;Setting Up NestJS for Validation.

&lt;ul&gt;
&lt;li&gt;Prerequisites and project setup.&lt;/li&gt;
&lt;li&gt;Creating and Using Validation Schemas&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Introduction to pipe and how to use it with Joi&lt;/li&gt;
&lt;li&gt;Validation on Param and Query Params using Joi.&lt;/li&gt;
&lt;li&gt;Practical Implementation: Explore a complete NestJS application utilizing nestjs-joi and joi-class-decorators on GitHub: &lt;a href="https://github.com/AliFathy-1999/nestJs-joi-sample-app"&gt;NestJS Sample App with nestjs-joi&lt;/a&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  1. Introduction to Data Validation in Web Applications.
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Data validation is the process of ensuring that data entered by users or obtained from external sources satisfies the specified criteria and format. Data validation can be done at several levels, including client-side, server-side, and database-level.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  2. Setting Up NestJS for Validation.
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;em&gt;&lt;strong&gt;Prerequisites and project setup:&lt;/strong&gt;&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  1. Install Node and npm :
&lt;/h3&gt;

&lt;p&gt;Make sure that you installed &lt;strong&gt;Node&lt;/strong&gt; on your device&lt;br&gt;&lt;br&gt;
&lt;code&gt;node -v&lt;/code&gt;  to detect whether you have installed the &lt;strong&gt;Node&lt;/strong&gt; or not. If you installed node output is &lt;code&gt;v20.13.1&lt;/code&gt; or any version. If you didn't install node output will be &lt;code&gt;node: command not found.&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;You need to install node by going to &lt;strong&gt;Nodejs website&lt;/strong&gt; &lt;a href="https://nodejs.org/en"&gt;NodeJS website&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Make sure that you installed &lt;strong&gt;Node Package Manager npm&lt;/strong&gt; on your device &lt;code&gt;npm -v&lt;/code&gt;  to detect whether you have installed the npm or not. If you installed npm output is &lt;code&gt;10.8.0&lt;/code&gt; or any version. If you didn't install npm output will be &lt;code&gt;npm: command not found.&lt;/code&gt; &lt;/p&gt;

&lt;h3&gt;
  
  
  2. Install NestJs and create new nestApp :
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i -g @nestjs/cli
nest new my-nestjs-app
cd ./my-nestjs-app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3. create a new pipe called validation:
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// --no-spec =&amp;gt; Disable spec files generation 
// --flat =&amp;gt; Do not generate a folder for the element.
nest g pipe validation --no-spec --flat
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4. Installing necessary packages (nestjs-joi, joi-class-decorators)
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i class-transformer joi nestjs-joi joi-class-decorators
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;em&gt;&lt;strong&gt;Creating and Using Validation Schemas:&lt;/strong&gt;&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  1. Create Endpoint '/testBody', Method type: Post,In app controller
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Body, Controller, HttpCode, HttpStatus, Post, Req, Res } from '@nestjs/common';
import { AppService } from './app.service';
import { Request, Response } from 'express';
import { validationBodyDto } from './validate.dto';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Post('/testBody')
  @HttpCode(HttpStatus.OK)
  testJoiValidation(@Req() req: Request, @Res() res: Response, @Body() reqBody: validationBodyDto) {
    const data = reqBody;
    res.json(data);
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2. Create Dto file called (validate.dto.ts) to validate this endpoint and create joi schema class (validationBodyDto):
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Expose } from "class-transformer";
import { JoiSchema, JoiSchemaOptions } from "joi-class-decorators";
import * as Joi from 'joi';

interface reviewInterface {
    rating: number;
    comment: string;
}
// @Expose ==&amp;gt; is used to mark properties that should be included in the transformation process, typically for serialization and deserialization. However.
// @JoiSchema() ==&amp;gt; Define a schema on a type (class) property. Properties with a schema annotation are used to construct a full object schema.


//It ensures strict validation by disallowing any properties that are not explicitly defined in your schema. 
@JoiSchemaOptions({
    allowUnknown: false
})

export class validationBodyDto {

    //Basic Validation is type string and required
    @Expose() @JoiSchema(Joi.string().trim().required())
    fullName: string;

    //Check on length, and is valid egyptian phone number
    @Expose() @JoiSchema(Joi.string().length(11).pattern(/^(011|012|015|010)\d{8}$/).required())
    phoneNumber: string;

    //Check is valid email
    @Expose() @JoiSchema(Joi.string().email().optional())
    email?: string;

    //Check value is valid in case of M or F only
    @Expose() @JoiSchema(Joi.string().valid('M', 'F').required())
    gender: string;

    //militaryStatus is mendatory if gender is M otherwise is optional
    @Expose() @JoiSchema(
        Joi.when('gender', {
            is: 'M',
            then: Joi.string().required(),
            otherwise: Joi.string().optional(),
        }),
    )
    militaryStatus: string;

    //Check age is number, min 14 and max age is 100
    @Expose() @JoiSchema(Joi.number().min(14).max(100).message('Invalid age'))
    age: number;

    //Check on Array of object is valid or invalid
    @Expose()
    @JoiSchema(
        Joi.array().items(
                Joi.object({
                        rating: Joi.number().min(0.1).required(),
                        comment: Joi.string().min(3).max(300).required(),
                    }).required(),
            ).required(),
    )
    reviews: reviewInterface[];

    //allow this field with empty string
    @Expose() @JoiSchema(Joi.string().allow('').optional())
    profilePicture?: string;

    //profileFileName is mendatory if profilePicture has an value otherwise it optional 
    @Expose() @JoiSchema(
        Joi.when('profilePicture', {
            is: Joi.string().exist(),
            then:  Joi.string().required(),
            otherwise: Joi.string().allow('').optional(),
    }))
    profileFileName: string;

    //Check if isVerified is boolean and required
    @Expose() @JoiSchema(Joi.boolean().required())
    isVerified: boolean;

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. Introduction to pipe and how to use it with Joi
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;In NestJS, a "pipe" is a class annotated with the @Injectable() decorator that implements the PipeTransform interface. Pipes are typically used for transforming or validating data. They can be used at various levels, including method-level, controller-level, or globally.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;em&gt;Introduction to Pipes&lt;/em&gt;&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Transformation&lt;/strong&gt;: Pipes can transform input data to a desired format.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Validation&lt;/strong&gt;: Pipes can validate the data before passing it to the request handler. If the data is invalid, the pipe can throw an exception, which will be handled by NestJS.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;In our case, we use it to transform plain object into a typed object so that we can apply validation.&lt;/li&gt;
&lt;li&gt;So let us use the validation pipe that we created before:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { BadRequestException, Injectable, PipeTransform, Type } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { getClassSchema } from 'joi-class-decorators';

@Injectable()
export class ValidationPipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    const { metatype } = metadata;
    const bodyDto = metatype; // Dto Schema
    /*
      To transform our plain JavaScript argument object into a typed object so that we can apply validation.
      The reason we must do this is that the incoming post body object, when deserialized from the network request, does not have any type information. 
    */

    // getClassSchema(bodyDto) ==&amp;gt; A function from joi-class-decorators to retrieve the Joi validation schema associated with a class.
    const bodyInput = plainToInstance(bodyDto, value); // Convert plain Dto object to instance to transform it manually
    const bodySchema = getClassSchema(bodyDto); // Get Joi Schema from Dto
    // Validates the class instance against the Joi schema. If validation fails, error will contain the validation errors.
    const error = bodySchema.validate(bodyInput).error;  
    if (error) {
      throw new BadRequestException(`Validation failed: ${error.details.map((err) =&amp;gt; err.message).join(', ')}.`);  
    }
    return value
  }
}
interface ArgumentMetadata {
  type: 'body' | 'query' | 'param' | 'custom';
  metatype?: Type&amp;lt;unknown&amp;gt;;
  data?: string;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;To use this validation pipe on our endpoint, we have four ways: 

&lt;ul&gt;
&lt;li&gt;Use &lt;strong&gt;Global scoped pipes&lt;/strong&gt;, It will be applied on every route handler across the entire application.
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// In main.ts
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  await app.listen(3000);
}
bootstrap();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Use &lt;strong&gt;parameter-scoped pipes&lt;/strong&gt;, It will be applied on param reqBody.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  @Post('/testBody')
  @HttpCode(HttpStatus.OK)
  testJoiValidation(@Body(new ValidationPipe()) reqBody: validationBodyDto, @Res() res: Response) {
    const data = reqBody;
    res.json(data);
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Use &lt;strong&gt;method-scoped pipes&lt;/strong&gt;, It will be applied on method testJoiValidation.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  @Post('/testBody')
  @HttpCode(HttpStatus.OK)
  @UsePipes(new ValidationPipe()) // Method Scope
  testJoiValidation(@Body() reqBody: validationBodyDto, @Res() res: Response) {
    const data = reqBody;
    res.json(data);
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Use &lt;strong&gt;controller-scoped pipes&lt;/strong&gt;, It will be applied on method testJoiValidation.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Controller()
@UsePipes(new ValidationPipe()) //Controller-scoped
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Post('/testBody')
  @HttpCode(HttpStatus.OK)
  testJoiValidation(@Body() reqBody: validationBodyDto, @Res() res: Response) {
    const data = reqBody;
    res.json(data);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4. Validation on Param and Query Params using Joi.
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Create an endpoint '/testParams/:category', method type: GET, It took param named category ('Fashions', 'Electronics', 'MobilesPhones', 'Perfumes') and two Query Params limit and page.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  @Get('/testParams/:category')
  @HttpCode(HttpStatus.OK)
  @UsePipes(new ValidationPipe())
  testJoiValidationParam(
    @Param() category: validationParamDto,
    @Query() limitAndPageSize: validationQueryParamDto,
    @Res() res: Response
  ) {
    res.json({
      category,
      limitAndPageSize
    });
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Create two dtos for those params:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export class validationParamDto {
    @Expose() @JoiSchema(Joi.string().valid('Fashions', 'Electronics', 'MobilesPhones', 'Perfumes').required())
    category: string;
}

@JoiSchemaOptions({
    allowUnknown: false
})

export class validationQueryParamDto {

    @Expose() @JoiSchema(Joi.number().min(0).max(100).message('Invalid limit'))
    limit: string;

    @Expose() @JoiSchema(Joi.number().min(0).max(100).message('Invalid page size'))
    page: string;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Finally, I want to thank you for taking the time to read my article and I hope this article is useful for you :).
&lt;/h3&gt;

&lt;p&gt;For hands-on implementation and further exploration, you can access the complete codebase of a sample NestJS application using nestjs-joi and joi-class-decorators on GitHub. The repository includes practical examples and configurations demonstrating how to integrate and leverage robust data validation in NestJS:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/AliFathy-1999/nestJs-joi-sample-app"&gt;Explore the NestJS Sample App on GitHub&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Feel free to clone, fork, or contribute to enhance your understanding and implementation of data validation in NestJS.&lt;/p&gt;

</description>
      <category>nestjs</category>
      <category>joi</category>
      <category>typescript</category>
      <category>node</category>
    </item>
    <item>
      <title>Why should we use Typescript with NodeJs and Express?</title>
      <dc:creator>AliFathy-1999</dc:creator>
      <pubDate>Wed, 29 Mar 2023 00:05:40 +0000</pubDate>
      <link>https://dev.to/alifathy1999/why-should-we-use-typescript-with-nodejs-and-express-gmf</link>
      <guid>https://dev.to/alifathy1999/why-should-we-use-typescript-with-nodejs-and-express-gmf</guid>
      <description>&lt;h1&gt;
  
  
  &lt;strong&gt;Here are some topics I can cover to explain why using Typescript with Node and Express is beneficial :&lt;/strong&gt;
&lt;/h1&gt;

&lt;h3&gt;
  
  
  1. What is Typescript and why is it useful in web development?
&lt;/h3&gt;

&lt;h3&gt;
  
  
  2. Why You Should Choose Typescript Over JavaScript?
&lt;/h3&gt;

&lt;h3&gt;
  
  
  3. How to set up TypeScript with Node.js and Express.
&lt;/h3&gt;

&lt;h3&gt;
  
  
  4. Best practices for using TypeScript with Node.js and Express.
&lt;/h3&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;1. What is Typescript?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fauo6sdmxd6b8uin3h5mv.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fauo6sdmxd6b8uin3h5mv.jpg" alt="Image description" width="800" height="718"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Typescript is a programming language that adds static &lt;strong&gt;typing&lt;/strong&gt;, &lt;strong&gt;compiling&lt;/strong&gt; and &lt;strong&gt;OOP&lt;/strong&gt; to JavaScript. It can be used for both client-side (Front-end Frameworks like &lt;strong&gt;Angular, React and vue&lt;/strong&gt;) and server-side applications (&lt;strong&gt;Nodejs&lt;/strong&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Why is it useful in web development?&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;It makes our code more secure and robust by preventing many bugs before the code is even shipped.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It catches problems during code development and integrates wonderfully with code editors like Visual Studio Code.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  2. Why You Should Choose Typescript Over JavaScript?
&lt;/h2&gt;

&lt;p&gt;Three reasons why you should choose TypeScript over JavaScript&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Typescript is an enhanced version of JavaScript.&lt;/li&gt;
&lt;li&gt;TypeScript makes it easier to write accurate code more quickly and catch bugs prior to runtime.&lt;/li&gt;
&lt;li&gt;TypeScript is more reliable and easier to refactor. This enables developers to avoid errors and do restructure much easier.&lt;/li&gt;
&lt;li&gt;TypeScript is more explicit. It takes our attention to make types explicitly on variables, return type and etc...&lt;/li&gt;
&lt;li&gt;TypeScript is an object-oriented scripting language. These features make it possible for developers to write more structured, maintainable, and scalable code.&lt;/li&gt;
&lt;li&gt;Dependent language (compiles to JavaScript).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;3. How to set up TypeScript with Node.js and Express.&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Favt52r9dimw68ot4njlr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Favt52r9dimw68ot4njlr.png" alt="Image description" width="800" height="312"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;h3&gt;
  
  
  Steps to setup Nodejs typescript project :
&lt;/h3&gt;

&lt;h3&gt;
  
  
  1. Install Node and npm :
&lt;/h3&gt;

&lt;p&gt;Make sure that you installed &lt;strong&gt;Node&lt;/strong&gt; on your device&lt;br&gt;&lt;br&gt;
&lt;code&gt;node -v&lt;/code&gt;  to detect whether you have installed the &lt;strong&gt;Node&lt;/strong&gt; or not. If you installed node output is &lt;code&gt;v18.15.0&lt;/code&gt; or any version. If you didn't install node output will be &lt;code&gt;node: command not found.&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;You need to install node by going to &lt;strong&gt;Nodejs website&lt;/strong&gt; &lt;a href="https://nodejs.org/en" rel="noopener noreferrer"&gt;NodeJS website&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Make sure that you installed &lt;strong&gt;Node Package Manager npm&lt;/strong&gt; on your device &lt;code&gt;npm -v&lt;/code&gt;  to detect whether you have installed the npm or not. If you installed npm output is &lt;code&gt;9.6.1&lt;/code&gt; or any version. If you didn't install npm output will be &lt;code&gt;npm: command not found.&lt;/code&gt; &lt;/p&gt;
&lt;h3&gt;
  
  
  2. Create a New Project Folder.
&lt;/h3&gt;
&lt;h3&gt;
  
  
  3. Start running npm in your project folder :
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Open a terminal.&lt;/li&gt;
&lt;li&gt;Run the command &lt;code&gt;npm init -y&lt;/code&gt; to initial npm and install packages.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  4. Add TypeScript as a dev dependency
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;npm install typescript --save-dev&lt;/code&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  5. Install ambient Node.js types for TypeScript :
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install @types/node --save-dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  6. Create &lt;code&gt;tsconfig.json&lt;/code&gt; :
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx tsc --init
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;Copy this in &lt;code&gt;tsconfig.json&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "compilerOptions": {
    "target": "es5",                          
    "module": "commonjs",                    
    "lib": ["es6"],                     
    "allowJs": true,
    "outDir": "dist",                          
    "rootDir": ".",
    "strict": true,         
    "noImplicitAny": true,
    "esModuleInterop": true,
    "resolveJsonModule": true
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  7. To reload server :
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install nodemon ts-node -D
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;nodemon&lt;/strong&gt; which is used to watch for changes to our code and automatically restart when a file is changed.&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;ts-node&lt;/strong&gt; for running TypeScript code directly without having to wait for it be compiled.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Add &lt;code&gt;nodemon.json&lt;/code&gt; file and write the following in it:&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "watch": ["./"],
    "ext": ".ts,.js",
    "ignore": [],
    "exec": "npx ts-node index.ts"
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  8. Write in &lt;strong&gt;scripts&lt;/strong&gt; in &lt;strong&gt;package.json&lt;/strong&gt;, to use it in running server :
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  "scripts": {
    "start:dev": "npx nodemon"
  },
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  9. Create our first TypeScript file &lt;code&gt;index.ts&lt;/code&gt;.
&lt;/h3&gt;
&lt;h3&gt;
  
  
  10. Create simple server using &lt;strong&gt;express&lt;/strong&gt; framework
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;First install express and @types/express
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i express
npm i @types/express -D
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;Write in &lt;strong&gt;index.ts&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import express,{ Application, Router ,Request, Response} from "express";

const app :Application = express();
var router :Router= require('express').Router();
const port :number = 3000;
app.use(router);

router.get("/", function (req:Request, res:Response) : void {
    res.send("&amp;lt;h1&amp;gt;Hello, I'm Ali Ahmed. I'm Software Engineer&amp;lt;/h1&amp;gt;");
  });
app.listen(port, () =&amp;gt; {
    console.log(`Server Running here 👉 http://localhost:${port}`);
})

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  11. Finally run this command to &lt;strong&gt;run server&lt;/strong&gt;
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm run start:dev 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Output will be :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt; testnodewithtypescript@1.0.0 start:dev
&amp;gt; npx nodemon

[nodemon] 2.0.22
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): **/*
[nodemon] watching extensions: ts,js
[nodemon] starting `npx ts-node index.ts`
Server Running here 👉 http://localhost:3000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;4. Best practices for using TypeScript with Node.js and Express.&lt;/strong&gt;
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. Use strict typing:
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "compilerOptions": {
    "strict": true
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;One of the key advantages of TypeScript is that it provides strong typing. &lt;/li&gt;
&lt;li&gt;Strict mode activates 2 main compiler options:

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;noImplicitAny&lt;/strong&gt; : explicit anys are not accepted by TypeScript.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;strictNullChecks&lt;/strong&gt; : will ask to tell when a value can be null.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  2. Use interfaces:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Interfaces are a powerful feature of TypeScript that allow you to define a contract for an object's properties and methods. This can help you catch errors at compile-time and make your code more organized and maintainable. Use interfaces to define the shape of your &lt;strong&gt;data models&lt;/strong&gt; and &lt;strong&gt;API responses&lt;/strong&gt;. By using an interface to define the shape of the user object, you can &lt;strong&gt;catch errors at compile-time if you try to assign the wrong type of data to a property&lt;/strong&gt;, or if you forget to include a &lt;strong&gt;required property&lt;/strong&gt;. This can help you write more reliable code and avoid common bugs.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// In API responses
import { Request, Response } from 'express';

interface User {
    id: number;
    name: string;
    email: string;
    socialMediaProfile:string[]
    createdAt: Date;
  }

function getUser(req: Request, res: Response): void {
    const user: User = {
        id: 1,
        name: 'Ali Ahmed',
        email: 'aliahmedfathi37@gmail.com',
        socialMediaProfile:[
            "linkedin.com/in/ali-ahmed-fathi", // linkedin profile
            "https://github.com/AliFathy-1999", //Github profile
        ],
        createdAt: new Date(),
      };
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//In Data models:

interface IUserModel{
    fname:String,
    lname:String,
    email:String,
    password:String,
}
const schema= new Schema&amp;lt;IUserModel&amp;gt;({
    fname:{
        type:String,
        required:true,
        trim:true,
        minlength:3,
        maxlength:20
    },
    lname:{
        type:String,
        required:true,
        trim:true,
        minlength:3,
        maxlength:20
    },
    email:{
        type:String,
        required:true,
        unique:true,
    },
    password:{
        type:String,
        required:true,
        trim:true,
        minlength:6,
    },
},{
    timestamps:true  //createdAt, updatedAt
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3. Use Generics:
&lt;/h3&gt;

&lt;p&gt;It helps developers to write more &lt;strong&gt;reusable and flexible code&lt;/strong&gt;. Use generics to write &lt;strong&gt;functions and classes that can work with different types of data.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/*
Let's say you have a function that takes an array of objects and returns an array of a specific property from each object. You can use generics to make this function work with any type of object and any type of property.
*/
  function myGeneric&amp;lt;T, K extends keyof T&amp;gt;(items: T[], key: K): T[K][] {
    return items.map(item =&amp;gt; item[key]);
  }
  const users: User[] = [
    { id: 1, name: 'Mustafa Mahmoud',socialMediaProfile:["",""], email: 'Mustafa@hotmail.com',createdAt:new Date },
    { id: 2, name: 'Bassem Mahmoud',socialMediaProfile:["",""], email: 'Bassem@hotmail.com',createdAt:new Date },
  ];

  const names = myGeneric(users, 'name'); // ['Mustafa Mahmoud', 'Bassem Mahmoud']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4. Use Async/Await:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;API endpoint that &lt;strong&gt;fetches some data&lt;/strong&gt; from a database using an asynchronous function.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  const getUserByEmail = async (req: Request, res: Response): Promise&amp;lt;void&amp;gt; =&amp;gt;{
    try {
        const { body: { email } } = req
      const data = await User.findOne({email});
      res.json(data);
    } catch (err) {
      res.status(500).json({ error: 'Internal server error' });
    }
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Finally, I want to thank you for taking the time to read my article and I hope this article is useful for you :).
&lt;/h2&gt;

</description>
      <category>typescript</category>
      <category>node</category>
      <category>webdev</category>
      <category>express</category>
    </item>
  </channel>
</rss>
