What is the process of generating a TypeScript error in an Express application?

After creating a typescript class controller, I purposely omitted the "email" property in the payload. Surprisingly, no typescript error was thrown stating something like "email(undefined) is not equals to email(string)".

The issue arises when it smoothly executes the "console.log" without any interruption by an error. I anticipated that it would halt the execution since it does not conform to the type "testType" (please correct me if I am mistaken).

I am curious to hear your insights on how to address this situation effectively.


type testType = {
  body: {
    email: string
    password: string
  }
}

class Testing {
  public static sampleFunc = async (req: testType, res: Response, next: NextFunction) => {
    const temp = req.body
    
    console.log('temp', temp);

    // ..more code here
    
    res.send('success');
  }
}

Answer №1

Typescript serves as a tool for static type checking and ultimately compiles down to javascript. This means that during runtime, the code being executed is actually the compiled javascript version. Consequently, typescript does not offer protection against passing properties with incorrect types.

In order to achieve your desired outcome, it is necessary to incorporate additional error handling within the code prior to processing the request.

For example:

class Testing {
  public static sampleFunc = async (req: testType, res: Response, next: NextFunction) => {    
    if (!req.email || !req.password) {
      throw new Error("No email / password provided");
    }
    
    res.send('success');
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensure that the interface limits the key value to match precisely the value of a constant in Typescript

Seeking assistance in understanding how to enforce a specific type for an optional key within an interface: const FIRST = "FIRST" const SECOND = "SECOND" interface TSomeInterface { element: Element order?: typeof FIRST | typeof ...

Can you explain why it prints to the console twice every time I try to add an item?

This is a note-taking application created using Angular and Firebase. The primary functionalities include adding items and displaying them. I noticed a strange behavior where my ngOnInit() method is being called twice every time I add an item. As shown in ...

When using NodeJS with Passport JWT (version 4.0.0), there is an issue with authenticating users through the POSTMAN Rest Client. Every

My backend framework is express js, and I am currently developing a login authentication module using Passport-JWT. I am looking to implement authentication middleware on private routes without having to repeatedly write passport.authenticate('jwt&ap ...

Running the NPM build command results in an error specifically related to an HTML file

I encountered an issue in my AngularJS application when running the command: npm run build -- -prod The error message I received was: ERROR in ng:///home/directoryling/appname-play.component.html (173,41): The left-hand side of an arithmetic operation ...

How can I prevent scrolling in Angular's cdk-virtual-scroll feature?

Is there a way to use Angular's cdk-virtual-scroll to prevent the scrollbar from moving by default? I have done extensive research but have not been able to find a solution. ...

typescript filter an array using another array

Struggling to find a solution... I am attempting to filter one array with another array. Here's the scenario: I have an array that needs to be filtered based on dynamically selected checkboxes. After trying various approaches, here is the code I hav ...

Using Angular 4 to monitor changes in two-way binding properties

Recently, I developed a unique toggle-sorting component that examines if the current sorting parameters align with its sorting slug and manages clicks to reflect any changes. // toggle-sorting.component.ts @Input() sortingSlug: string; @Input() currSorti ...

Dynamic Object properties are not included in type inference for Object.fromEntries()

Hey there, I've been experimenting with dynamically generating styles using material UI's makeStyles(). However, I've run into an issue where the type isn't being correctly inferred when I use Object.fromEntries. import * as React from ...

Tips for Providing a Generic Type to a Component Imported Using Next.js Dynamic

There is no issue with this code snippet: import DatasheetContainer from '@/uikit/detailed-view/DatasheetContainer'; const DetailedView = () => { return ( <Page> <PageBody direction="row" bgColor="white&qu ...

Issue with Angular 7 ngZone causing undefined error

I've been struggling to display a 3D object using three.js. Every time I attempt to start the animation loop (within ngAfterViewInit), I keep encountering the same error: TypeError: Cannot read property 'ngZone' of undefined In an effort t ...

What is the best approach to dealing with "Cannot <METHOD> <ROUTE>" errors in Express?

Here is a simple example to illustrate the issue: var express = require('express'); var bodyparser = require('body-parser'); var app = express(); app.use(bodyparser.json()); app.use(errorhandler); function errorhandler(err, req, res, ...

Unable to establish a connection with the endpoint

I'm encountering an issue while trying to connect to the endpoint on the server. Below is the code snippet: Register.jsx function Register() { const [registerUser, setRegisterUser] = useState({ username: "", email: "", password: "", ...

The '&&' operator cannot be used with method groups in the tst file

I am currently facing an issue while trying to verify a condition in the tst (typescript generator) file within my C# application. The error message I am encountering states that the Operator '&&' cannot be applied to operands of type 'metho ...

Nodemon has unexpectedly stopped running and is now patiently waiting for a file to be modified

const express = require("express"); const app = express(); const PORT = process.env.PORT || 3000; const products_routes = require("./routes/products"); app.get("/", (req, res) => { res.send("Welcome to my API&q ...

Express.js Issue: Error in JSON Object Returned When Date Parameter is Empty

Currently tackling the challenges of the FreeCodeCamp Timestamp Microservice project and facing a roadblock in the implementation. While most requirements are met successfully, there's an issue with handling an empty date parameter test case. Let me b ...

Steps for redirecting to an external URL with response data following an HTTP POST request:

this.http.post<any>('https://api.mysite.com/sources', [..body], [...header]) .subscribe(async res => { const someData = res.data; const url = res.url; window.location.href = url }) After redirecting to the specified UR ...

Combine two observables that contain different data types

Here are the functions I am working with: getNetworkByName(prefix: string): Observable<Network[]> { return this.http.get<Network[]>(this.Url + '/networks/search?name-prefix=' + prefix) .catch(handleError); } and getNetwork(id: ...

Node.js and Express: The error message "Cors is not a function"

Everything was running smoothly until this morning when out of nowhere, a type error popped up stating that Cors is not a function Here's my code: import * as Cors from "cors"; ... const corsOptions: Cors.CorsOptions = { allowedHeaders: ["Origi ...

Angular 8: Master the art of HTML binding

I am facing an issue with displaying HTML content in Angular 8. **Note: The HTML template I receive from the database as JSON data needs to be displayed in Angular. I am fetching this template and saving it in a variable (e.g., plot), then passing that va ...

What could be causing the error in the console when I try to declare datetime in Ionic?

I am just starting out with Ionic and Angular, but I seem to have hit a roadblock. The compiler is throwing an error that says: node_modules_ionic_core_dist_esm_ion-app_8_entry_js.js:2 TypeError: Cannot destructure property 'month' of '(0 , ...