Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

196
Views
Extracting values from json request (which could possibly undefined)

I am trying to learn typescript/js and one of thing i am doing is implement a rest-api using aws-lambda (severless tack). Now, I need to extract body payload to either a construct or just assign those values to variables.

Lets say I am sending following request to signup a user

POST {{userApiEndpoint}}/signup HTTP/1.1
content-type: application/json

{"username":{{username}},"password":{{password}}}

Now I want to extract this username and password from event.body. I have tried multiple things and everytime i am getting errors of string | undefined can't be assigned to string or something similar.

Things that i have tried

export interface User {
  username: string | undefined;
  password: string | undefined;
}

Option 1: const newUser = event.body? as User; got an error that says Cannot find name 'as'

Option 2: const newUser = event.body as User; got an error which says Conversion of type 'string | undefined' to type 'User' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

Option 3: const body = JSON.parse(event.body); got an error which says Argument of type 'string | undefined' is not assignable to parameter of type 'string'.

I am not sure what else to try.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Option 3 should work.

Edit: unless you have explicitly typed your event type as APIGatewayProxyEventV2, in which case the body is of type string | undefined, and the user is:

user = JSON.parse(event.body ?? "") as User

export interface User {
  username: string | undefined;
  password: string | undefined;
}

// event explicitly typed as APIGatewayProxyEventV2
// the body is typed as string | undefined
const event = {body: '{"username": "foo", "password": "bar"}'} as Record<string, string | undefined>
const user = JSON.parse(event.body ?? "") as User
console.log(user.password)

// Option 3
// the body is typed as any
const event1 = {body: '{"username": "foo", "password": "bar"}'} as Record<string, any>
const user1 = JSON.parse(event1.body) as User
console.log(user1.password)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!