Transforming an object into an interface in TypeScript

Recently, I have started learning Typescript and am currently working on a project where I am building a REST API. In this project, I have defined a specific model for my request payload.

However, even after typecasting, the type of 'resObj' remains as an object when I want it to be of type 'requestObj'.

 export const funcName = async function (req: Express.Request, res: Express.Response) {

        console.log(typeof req.body)  // object
        const resObj : requestObj  =  req.body as requestObj 
        console.log(typeof resObj)  // object.     but it should be requestObj

export interface requestObj {
    to:  string ,
    name: string,
    phoneNo : string, 
}

This is causing issues with data validation. Despite searching extensively, a viable solution still eludes me.

Answer №1

When TypeScript is compiled to JavaScript, the resulting file does not contain a type specifically named requestObj. Instead, all objects are categorized as type object. It's important to note that in TypeScript, types only exist before compilation. To validate types within TypeScript, conditional types should be utilized instead of relying on javascript's 'typeof' function.

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

I'm struggling to figure out how to implement express routing

In one of my files, named index.js, I have the following code... const express = require('express'); const app = express(); app.use(express.json({ extended: false })); app.use('/api/users/', require('./users/routes')); con ...

Verify whether the object is properly implementing the interface

Design: export interface Person { id: number; firstName: string; lastName: string; age: number; } Is there a way to verify that an object returned from the backend aligns with the structure defined in the Person interface? ...

Struggling with Running the Webpack serve Command

Struggling to set up a React app using Webpack and Babel. After following various tutorials on YouTube and other websites, I keep encountering the same error whenever I run the webpack serve command, even if my index.js file is empty. [ERROR]: ERROR in .. ...

Instead of JSON data, HTML is being transmitted

I'm facing an issue where I am attempting to retrieve data from a SQL database and showcase it on a Reactjs web app. However, each time I make a call to the database, the HTML content of the current webpage is displayed instead. I have ensured that th ...

The 'type' property within the NGRX Effect is not present in the type Observable<any[]>

I am currently in the process of upgrading my Angular app from version 6 to version 7. Additionally, I am upgrading the TypeScript version from 2.7.2 to 3.1.6. The issue I'm encountering is that TypeScript is flagging an error stating that my ngrx ef ...

What could be causing the malfunction in this JavaScript and WebRTC code?

<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Vid Chat App</title> </head> <body> <video controls autoplay> </video> <script src="https: ...

Unable to locate the 'react-native' command, attempted various fixes but none were successful

Working on an older react native project that was functioning perfectly until I tried to pick it back up and encountered a problem. https://i.stack.imgur.com/1JUdh.png This issue revolves around the package.json file. https://i.stack.imgur.com/v6ZEf.png ...

Duplicate items within an array were found when receiving Node.js response data in Angular

I'm facing an issue where duplicate elements are being displayed in an Angular table when receiving data from Node.js. The array sent by Node.js contains 2 elements, but somehow it appears as 4 elements in the Angular table. This discrepancy is puzzli ...

A Comprehensive Guide: Obtaining the Final Tab from a JSON using API

What is the method to extract the last tab from a given JSON code? { "claimed_levels": { "level_1", "level_2" } } I want to display the level when someone types "!levels". The desired output format should be: Your current level is "2" ...

Using TypeScript arrow functions to define parameters

When setting "noImplicitAny": true in TypeScript, you may encounter the following errors: Parameter 'x' implicitly has an 'any' type This error can occur with the code snippet: .do(x => console.log(x)); Another error you might s ...

I encountered an error message saying "TypeError: response.json is not a function" while attempting to make a request using fetch in a project involving ReactJS and Node

Currently, I am in the process of developing a webpage using reactjs and have set up a simple REST api/database with nodejs. My main focus right now is on properly utilizing this API from the front end. The objective was to send a JSON payload containing { ...

Is there an Atom package available for node.js similar to Emmet for providing autocomplete functionality?

Is there an Atom package available for autocompleting Node.js code like Emmet? ...

Server nearby designated to handle requests to the api

Currently, I am working on a project involving automation. Within Adobe CEP, there is a local server that operates on Node.js/Express. My goal is to send an API request from a cloud server to this local server. How can I establish a connection between my l ...

Using AngularJS `$state.go` to navigate without redirection in ExpressJS

I'm facing a strange issue with my ExpressJS setup for serving AngularApp Files locally. I have a main controller with the following code snippet: else{ console.log('Forwarding to Login'); $state.go('signin&apos ...

Establish a connection between MongoStore and a database, while also authenticating with the admin credentials

How can a MongoStore be initialized to connect to a database and authenticate with the "admin" one? Can it be achieved similar to this using mongoose: var db = mongoose.createConnection('mongodb://myname:mypwd@localhost:27017/mydb', { auth: { a ...

Determining whether a request should be processed by a middleware in an Express application dynamically

New Beginnings: As a newcomer to the world of Epxress, I recently built a middleware for checking user credentials. Here is how I specified it: var check = function(req, res, next){/* checking user cred*/} I then used it in my code like this: app.use(c ...

Is Express.js compliant with RFC-3986 when handling query strings?

Does ExpressJs follow the RFC-3986 standard when decoding query string parameters? Why does it accept the direct character "è" but not the encoded version "%E8"? Test Expressjs http server 'use strict'; const express = require('express&ap ...

Setting up Node and NPM on Laradock can streamline your development

After carefully following the steps outlined in the documentation to enable NPM on my workspace, I encountered an issue. Upon running docker-compose exec workspace bash and checking for node -v, it was not installed as expected. The document does not pro ...

npm encountered an error stating that in the start command, the path must be specified as a string for

Trying to understand why my start npm script on my Mac is showing this error: path.js:8 throw new TypeError('Path must be a string. Received ' + ^ TypeError: Path must be a string. Received undefined at assertPath (path.js:8:11) ...

What is the method for ensuring TypeScript automatically detects the existence of a property when an object is statically defined?

In my software, I have an interface that serves as a base for other types. To simplify things for this discussion, let's focus on one specific aspect. This interface includes an optional method called getColor. I am creating an object that implements ...