event-mocks icon indicating copy to clipboard operation
event-mocks copied to clipboard

Body type is not assignable to type string error

Open iby opened this issue 6 years ago • 4 comments
trafficstars

The API Gateway example doesn't compile in TypeScript:

TS2322: Type '{ first_name: string; last_name: string; }' is not assignable to type 'string'.

The body is expected to be a string.

iby avatar Oct 21 '19 05:10 iby

Having the same issue over here:

Type '{ first_name: string; last_name: string; }' is not assignable to type 'string'.ts(2322)
index.d.ts(80, 5): The expected type comes from property 'body' which is declared here on type 'APIGatewayProxyEvent'

mgarciadelojo avatar Nov 12 '19 16:11 mgarciadelojo

Looking at the tests for this project, the call to createEvent is defined in a more lax way. This way worked for me over the examples shown in the README.

https://github.com/serverless/event-mocks/blob/074ef2901f8592b3d865a3794ec0477d2d6fecf7/lib/index.spec.ts#L39-L44

martysweet avatar Nov 25 '19 10:11 martysweet

Cool but having to cast it as 'any' seems a bit awkward? I've hit a similar issue today and I'm left in a situation where I might as well just mock out the entire event myself and ditch this library.

james-gardner avatar Nov 19 '20 11:11 james-gardner

Casting to any will work but I believe this issue is because the type of the body param isn't taking into account that some of the required params are supplied by the template.

https://github.com/serverless/event-mocks/blob/master/lib/index.ts#L51

body: typeof dictionary[T],

could instead be defined as

body: Partial<typeof dictionary[T]>,

Even then that's not quite accurate since it'll make all of the properties optional. Even better would be to let the body parameter's type be the type for the corresponding event but with the required fields that are provided by the template marked as optional. I think that's pretty tricky to accomplish dynamically since there isn't a native "merge" type that does what I'm suggesting. Perhaps it'd be more realistic to maintain that type manually but that has its own host of problems.

joshyork avatar Mar 09 '21 02:03 joshyork