DEV Community

Paul Walker
Paul Walker

Posted on • Originally published at solarwinter.net on

Typescript and hapi payloads

I’ve spent a bit of time on this over the last couple of days - it’s probably really obvious to people more familiar with Typescript, but I’m getting there. :-)

The problem

Typescript kept complaining when I used fields from the payload object:

src/code.ts:65:37 - error TS2339: Property 'previousUrl' does not exist on type 'string | object | Buffer | Readable'.

Enter fullscreen mode Exit fullscreen mode

And it’s not wrong - that property doesn’t exist there.

Since the type of payload is already declared, I couldn’t just declare a new interface with a different value.

A solution

I’m not claiming this is the best solution necessarily, but it does work, and it seems in keeping with the whole Typescript approach of “don’t make things an any object”.

What I did was define a new interface:

interface myInterface {
    previousUrl: string
};

Enter fullscreen mode Exit fullscreen mode

And then use payload as that:

h.redirect((request.payload as myInterface).previousUrl);

Enter fullscreen mode Exit fullscreen mode

A note on hapi

I thought I’d try hapi after using Express for a while. I’m still learning the patterns, but so far it seems nice, actually. It follows the “batteries included” approach from Python, but the batteries are plugins, so you only import the ones you want.

Latest comments (0)