1

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.

Em Ae
  • 8,167
  • 27
  • 95
  • 162

1 Answers1

1

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)
fedonev
  • 20,327
  • 2
  • 25
  • 34
  • I have this line `const newUser = JSON.parse(event.body) as User;` and it gave me same error i.e., `Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.ts(2345) (property) APIGatewayProxyEventV2.body?: string | undefined` – Em Ae Nov 08 '21 at 18:18
  • @EmAe `user = JSON.parse(event.body ?? "") as User` see earlier edited answer. The OP did not contain the `APIGatewayProxyEventV2` type reference. – fedonev Nov 18 '21 at 14:34