简体   繁体   中英

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 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; 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. 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'. Argument of type 'string | undefined' is not assignable to parameter of type 'string'.

I am not sure what else to try.

Option 3 should work. The following compiles without error on the typescript playground

// Option 3

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

const event = {body: '{"username": "foo", "password": "bar"}'} as Record<string, any>
const user = JSON.parse(event.body) as User

console.log(user.password)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM