Unpacking objects in Typescript

I am facing an issue with the following code. I'm not sure what is causing the error or how to fix it. The specific error message is:

Type 'CookieSessionObject | null | undefined' is not assignable to type '{ token: string; refreshToken: string; }'.
  Type 'undefined' is not assignable to type '{ token: string; refreshToken: string; }'
...
  namespace CookieSessionInterfaces {
    interface CookieSessionObject {
      token?: string;
      refreshToken?: string;
    }
  }
}

const currentUser = async (req: Request, res: Response, next: NextFunction) => {
  const { token, refreshToken }: { token: string, refreshToken: string } = req.session;
...

Additionally, req.session?.token and req.session?.refreshToken are functioning properly.

Answer №1

req.session may be null or undefined. Therefore, in this scenario, you can address it as follows:

type Tokens  = {
    token?: string, 
    refreshToken?: string
}

const { token, refreshToken }: Tokens = req.session || {token: null, refreshToken: null}

Alternatively, if session is either undefined or null, you could choose to throw an exception which can be caught later and managed accordingly.

if (!req.session) {
        throw new UnauthorizeException()
}

const { token, refreshToken }: Tokens = req.session

Your UnauthorizeException might be a custom exception or you could opt for a generic one instead.

In case you are implementing a callback function, remember to call the callback instead of throwing an exception.

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

Create a POST request to the server using Express.js

I'm facing a minor problem with something I had assumed was doable. I am aiming to create two express routes – one as a GET route named /post-data and another as a POST route called /post-recieve. The code snippet would appear like the following: ...

What are the steps to integrate Webpack into an EJS Reactjs Express MongoDb application?

I have incorporated EJS, Express/NodeJs, and MongoDB into the project, along with ReactJs as an addition. My next step is to introduce Webpack for bundling both EJS and ReactJs files together. Although the end goal is to transition the p ...

The HttpInterceptor is programmed to identify and capture 401 error responses

After successfully implementing a code that called a logout() method upon receiving a 401 response from the server, I encountered issues following an upgrade of Angular from 5.2 to 7.0.3. It seems like either the HttpInterceptor interface has been modified ...

Navigating to view component in Angular2 Routing: Issue with router-link click event not working

I have set up my app.routes.ts file and imported all the necessary dependencies. Afterward, I connected all the routes to their respective Components as follows: import {ModuleWithProviders} from '@angular/core'; import {Routes, RouterModule} f ...

What is the best way to retrieve an object instead of an array?

When attempting to retrieve a JSON Object, I unexpectedly received an array instead. My query is based on the primary key, so I anticipate only one result. This is my current method : router.get("/student_info/:id", (req, res, next) => { connecti ...

Using Axios with Mongoose to Update Documents in Not Working State

I'm currently working on implementing an edit feature for updating posts. My goal is to initially update a specific post by its ID and then make it more dynamic. Although I am able to successfully send a PUT request using axios, I'm not getting ...

Can one create a set of rest arguments in TypeScript?

Looking for some guidance on working with rest parameters in a constructor. Specifically, I have a scenario where the rest parameter should consist of keys from an object, and I want to ensure that when calling the constructor, only unique keys are passed. ...

How can I update the folder from which socket.io retrieves the socket.io.js JavaScript file?

The declaration <script src="/socket.io/socket.io.js"></script> seems to be targeting socket.io.js in the 'public' directory instead of node_modules. Even changing the URL to ../node_module/socket.io/socket.io.js doesn't solv ...

Perplexed by the persistent failure of this Jasmine test accompanied by a vexing "timer in queue" error

I'm attempting to test a function that uses RxJS to broadcast long press events to subscribers. Below is the implementation of the function: export function watchForLongPress(target: HTMLElement) { let timer: number; const notifier = new Subject& ...

How to implement a timeout feature in JavaScript/TypeScript for cloud functions

I'm currently facing an issue with trying to delay certain actions using Cloud Firestore. Despite my attempts, the setTimeout/setInterval functions don't seem to be working as expected in my code. export const onTimerCreate = functions.firestore ...

The logout function in my React application isn't functioning properly, yet it seems to be working fine when

On my application page, I have a logout button in react. When clicked, the onClick event handles the request as shown below: async function logOutHandle(e){ e.preventDefault(); try { const response = await axios.post("http://loca ...

Performing multiple SQL queries in a for loop using Node.js and Express

After submitting a Post form, I receive a req.body containing multiple values in the following format: console.log(req.body) { productid:[1, 2, 3] qty: [3, 5, 6] } I'm trying to implement a for loop to use these values in SQL queries. However, I e ...

Storing and Retrieving Cookies for User Authentication in a Flutter Application

I am currently working on developing a platform where, upon logging in, a token is created and stored in the cookie. While I have successfully implemented a route that stores the cookie using Node.js (verified in Postman), I encounter issues when attemptin ...

The Azure GraphQL serverless function encountering an issue with the Cosmos DB connection, displaying an

After developing a serverless GraphQL API function using Azure functions and connecting it to Cosmos DB, I have encountered an issue with "Invalid URL" that has been puzzling me for a week. Despite running the graphql function locally without any problems, ...

An issue has been encountered: No NgModule metadata was discovered for 'AppModule' in the ngx-rocket Metronic theme

Task List [ ] Initialize [x] Build [x] Serve [ ] Test [ ] End-to-End test [ ] Generate [ ] Add [ ] Update [ ] Lint [ ] Internationalization [ ] Run [ ] Configure [ ] Help [ ] Version [ ] Documentation Is this a regression? This issue started occurring ...

What is the method for defining the href attribute using the parameter passed through ejs?

For my node.js express application, I am utilizing ejs as the view engine. One of the pages in this application is a profile page that displays a user's information. Within this page, there is an anchor tag with the user's email address as the va ...

Keep verifying the boolean value repeatedly

I've been working on implementing infinite scroll functionality for my card elements. Within my data.service file, I have a variable called reload that is utilized to determine whether more data needs to be loaded. This variable is set to true when th ...

What is the best way to handle a ReadableStream for a POST request?

I'm currently working on implementing basic CRUD operations using the latest Next.js 13 route handlers in combination with Prisma using TypeScript. This is how my POST request handler appears: export async function POST(req: NextRequest) { const c ...

What is the correct way to format responses written within response.write() in NodeJS?

Just starting out with NodeJS and express and following a tutorial on displaying two headings in the browser. Came across an issue where using res.send() twice wasn't working, so my instructor introduced me to the write method. Interestingly, when she ...

Utilizing GET requests to display varying results from MongoDB queries on a single webpage

I want to enhance my website by adding a search bar in the top section that retrieves a single document (ink) from a mongo database. Additionally, I am looking to display all documents from the same database on the same page. The challenge I am facing is ...