The request body doesn't meet the interface requirements, but it does not trigger an error response

I created a specific interface called NewTransactionPayload to ensure that only objects of this type are accepted in the request body. Strangely, TypeScript does not show any errors when I host the application. Why is that?

// Sample interfaces
interface NewTransactionPayload {
   transactionAmount: Number;
   transactionDate: String;
   transactionWallet: String;
   transactionPocket: String;
   transactionTag: String;
   transactionDetails: String;
}


transactionsRouter.post('/api/transactions', (req, res)=>{
    try {
        const newTransaction:NewTransactionPayload = req.body;
        // const newTransaction = req.body;
        res.status(201).json(newTransaction);
    } catch (err){
        res.status(400).json({error: `Bad request. ${err}`})
    }
});

Answer №1

TypeScript is an enhanced version of JavaScript that enforces type checking during compilation to catch errors early on. By detecting syntax errors and ensuring type safety before runtime, TypeScript helps prevent potential errors in your code.

Unlike some other languages, TypeScript does not conduct runtime type checks because it eliminates types during the compilation process for improved performance. Runtime type checking can introduce unnecessary overhead.

If runtime type validation is necessary, external libraries like Zod can be utilized. Zod offers comprehensive runtime type validation capabilities for TypeScript, allowing validation of variable types, expressions, and objects during execution.

Source:

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

Inject a value sent from response.render directly into the script tag

Below you will find a pug snippet. I am looking for a way to dynamically insert the user value into the chatConfig object. script. var chatConfig = { user : 'foo', pass : 'bar', } When rendering from my Express applicatio ...

Asserting within a specific condition's scope in TypeScript

I am facing a similar situation, type Field1Type = { a: string; } type Field2Type = { b: string; c: number; } type ObjType = { field: Field1Type | Field2Type } const field = { b: "" c: 0 } const obj = { field } as ObjType i ...

Issue with exporting Typescript React component

Despite searching for answers, none of the related questions have been helpful... My goal is to export React components from a TypeScript library that I plan to publish on npm. For testing purposes before publishing, I am utilizing npm link. The structu ...

Unable to establish SocketIO callback from client to server resulting in a null object instead

I'm encountering an unusual issue with SocketIO. On the server-side, I am using the emit() method like this: $s.sockets.emit(scope, {some: datas}, function(feedback) { console.log('received callback'); } ) ...

I encountered a problem where the error "Type '(err: Error) => void' does not possess any properties similar to type 'QueryOptions'" appeared, and I am unsure of the underlying cause

Check out my route for removing a user: https://i.stack.imgur.com/fevKI.png I've set up a route called "/deleteuser" that uses the POST method. It validates the request body for an id and then proceeds to delete the user with that ID from the databas ...

Creating spec.ts files for components by hand: A guide

Currently, I am facing an issue where the automatic generation of spec.ts files has been disabled by the developers when they created the components. To address this, I manually created the spec.ts files by copying over an existing one into each component, ...

Using axiosjs to send FormData from a Node.js environment

I am facing an issue with making the post request correctly using Flightaware's API, which requires form data. Since Node does not support form data, I decided to import form-data from this link. Here is how my code looks like with axios. import { Fl ...

The stylesheet was denied application due to its MIME type, transitioning from ATOM.io to Google Chrome was unsuccessful

Hi everyone, I'm a beginner programmer seeking some advice. I am currently working on launching a website but encountering an issue with my stylesheet not loading properly. The error message reads: "Refused to apply style from 'http://localhost: ...

I received an Internal Server Error (500) message from my application's console stating "GET http://localhost:3000/test"

I'm new to Node.js and I'm facing major challenges in getting my React app to work with it. I've built an API that functions correctly, as I can see the database elements when I run "node server.js". However, whenever I try to make these req ...

Need for input

I am working on organizing my routes in a separate file from app.js. The login route requires access to a Firebase instance. routes/auth.js var express = require('express'); var router = express.Router(); module.exports = function(firebase) { ...

What is the proper way to compare enum values using the greater than operator?

Here is an example enum: enum Status { inactive = -1, active = 0, pending = 1, processing = 2, completed = 3, } I am trying to compare values using the greater than operator in a condition. However, the current comparison always results in false ...

Having trouble retrieving a value from the img.onload event handler. A 'boolean' type error is being thrown, indicating it cannot be assigned to type '(this: GlobalEventHandlers, ev: Event) => any'

In my Angular application, I have implemented a method that verifies the size and dimensions of an image file and returns either false or true based on the validation result. Below is the code snippet for this function: checkFileValidity(file: any, multipl ...

Difficulty encountered when transferring data between React frontend and Node Express backend (CORS and API endpoints)

Encountering an issue where submitting form data results in a 404 error stating the endpoint is not found. The server.js file can be reviewed for further details on how to set up sending an email from the node express server upon passing data through the b ...

User interaction with a checkbox triggers a state change in Angular

Here is the code snippet I am working with, where clicking should set the checked value to false: @Component({ template: ` <input type="checkbox" [checked]="checked" (change)="onChange()"> ` }) export class AppC ...

Navigating with nodeJS

Currently, I am in the process of learning how to create a Node.js project. My latest endeavor involved following a tutorial to develop a chat application. However, it seems like there is an issue with the routing between the server side and client side. ...

Issue with Plesk Obsidian, IISNode, and Express - application functioning solely in local environment

After setting up my Node.JS + Express.JS application on my server with IISNode and Plesk Obsidian, browsing the page in a browser triggers an error: I have already verified the permissions of the relevant folders and ensured that the "App Identities" have ...

Using custom types for prop passing in Next.js with TypeScript

After making a http call, I obtain an array containing JSON data. This data is then assigned to a type called Service. type Service = { id?: string; name?: string; description?: string; }; The api call is made in getServerSideProps and the Service type is ...

Start up the Express server whenever the React application is launched in a web browser

I recently created a basic react app that communicates with an express server. When running on my local machine, I can start the server with the command nodemon server.js and my react app successfully sends requests to the server (which handles email commu ...

Error: Undefined property 'showMessageBox' cannot be read in Electron for Node.js

Here is a snippet of code that showcases how to utilize the dialog box feature using the electron node module. app.js const { dialog } = require('electron') const response = dialog.showMessageBox(null); console.log(response); I am ...

Error message: "No schema found for model 'User'.Create a schema using mongoose.model(name, schema)" with identifier 'MissingSchemaError'

I have been working on developing a schema for a user authentication system but keep encountering the error message mentioned above. I recently created two new pages with the code provided below: Users.js var mongoose = require ('mongoose'); va ...