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

Send a middleware out of a middleware function

I'm currently utilizing express-validator and I'm looking to implement varying checks based on a value in the request body. Although I've created a function for this purpose, it seems that I'm not receiving any responses back from expr ...

Using JavaScript, generate an array of objects that contain unique values by incrementing each value by 1

I have an array of objects called arrlist and a parameter uid If the property value has duplicate values (ignoring null) and the id is not the same as the uid, then autoincrement the value until there are no more duplicate values. How can I achieve the a ...

In the given situation, which would be the preferable option - making use of useEffect or opting for

My custom hook fetches data from a smart contract as shown below: export const usePoolLength = () => { const [length, setLength] = useState(0); const _getPoolLength = useCallback(async () => { const poolLength = await getPoolLength() ...

Unlocking the potential: passing designated text values with Javascript

In my current React code, I am retrieving the value from cookies like this: initialTrafficSource: Cookies.get("initialTrafficSource") || null, Mapping for API const body = {Source: formValue.initialTrafficSource} Desired Output: utmcsr=(direct)|utmcmd=(n ...

Is there a way to point the Facebook crawler bot to a different page?

I have a small website built with PreactJS that includes some parts from the main website (PHP). Since Facebook bot cannot crawl pre-rendered JavaScript content when shared, I want to redirect it to crawl the main PHP website instead when a link to the Pre ...

Jade is throwing an error due to an Unexpected token {

There seems to be an unexpected error popping up around line 18-19 (specifically in the dayClick function). The error message reads: Unexpected token { at Function (native) at assertExpression (C:\websites\timeoffcalendar\node_module ...

Developing a barrel component in React (utilizing .tsx)

My current directory structure looks like this: src assets components models counter.tsx index.ts The code found inside models/index.ts (also known as the barrel file) export * from "./counter"; The code within models/counter.ts export default in ...

What could be the reason for TypeScript throwing an error that 'product' does not exist in type '{...}' even though 'product' is present?

Structure of Prisma Models: model Product { id String @id @default(auto()) @map("_id") @db.ObjectId name String description String price Float image String createdAt DateTime @default(now()) updatedAt Da ...

Creating a Jsonifiable type that aligns with static interfaces: A step-by-step guide

When working with Typescript, there are 3 types that share similarities as they are composed of primitive types, maps, and arrays: type Color1 = { [component: string]: number } type Color2 = { green: number red: number blue: number } interface Colo ...

Can you suggest any alternative methods to stop the express sessions from expiring after every server restart without relying on RedisStore?

Even if the server restarts, I am still able to carry out various operations on the dashboard without having to reload the webpage ...

Struggling to resolve the unspecified outcome of an await operation

I'm looking to implement password comparison using the Bcrypt library. Here is the code snippet: bcrypt.js const bcrypt = require('bcrypt'); const saltRounds = 10; var Bcrypt = () => { } Bcrypt.encrypt = async function(password) { ...

Discover the simple steps to include row numbers or serial numbers in an angular2 datagrid

Currently, I am utilizing angular2 -datatable. Unfortunately, I am facing an issue where the correct row numbers are not being displayed in their corresponding rows. Whenever a user moves to the next page using the paginator, the datatable starts countin ...

The http post request is functioning properly in postman, but it is not working within the ionic app

I am currently developing an app in ionic v3 within visual studio (Tools for Apache Cordova). On one of the screens in my app, I gather user information and send it to an API. However, I'm encountering an issue with the HTTP POST request that I'm ...

When adding new elements to an array, the IDs of all objects become identical

When running the code below: dietDay.meals.forEach((meal) => { meal.mealProducts.forEach((mealProduct) => { if ( mealProduct.product.id && this.fetchedProductIds.includes(mealProduct.p ...

Ways to Safeguard Your API Key with HERE Map on the Client-Side

My current challenge involves concealing my API key from being visible in the network tab of a browser. Below are some GET requests I made to HERE Map, where the API key is exposed: https://1.base.maps.ls.hereapi.com/maptile/2.1/info?xnlp=CL_JSMv3.1.30.4&a ...

retrieve document data from firestore using the service

Is there a way to get real-time data from a Firestore document using a service? According to Firebase's documentation, you can achieve this by following this link: https://firebase.google.com/docs/firestore/query-data/listen?hl=es#web-modular-api I ...

Utilize the identical function within the reducer for numerous mat-slide-toggle and checkboxes in component.html

I'm currently diving into the world of Angular and ngrx while tackling a project focused on enabling users to create forms. In this project, users can add various form elements (such as labels, text fields, dropdown menus, checkboxes, etc.) from a sid ...

Conceal a designated column within a material angular data table based on the condition of a variable

In the morning, I have a question about working with data tables and API consumption. I need to hide a specific column in the table based on a variable value obtained during authentication. Can you suggest a method to achieve this? Here is a snippet of my ...

Is it possible to eliminate a parameter when the generic type 'T' is equal to 'void'?

In the code snippet below, I am attempting to specify the type of the resolve callback. Initially: Generic Approach export interface PromiseHandler<T> { resolve: (result: T) => void // <----- My query is about this line reject: (error: a ...

Is it possible for a class that implements an interface to have additional fields not defined in the parent interface?

Looking at the code snippet below, my aim is to ensure that all classes which implement InterfaceParent must have a method called add that takes an instance of either InterfaceParent or its implementing class as input and returns an instance of InterfacePa ...