1
votes

This isn't a specific koa question even though all the code is using koa, I'm just new to node and the module system.
When using Koa every request is defined by the Request interface:

declare module "koa" {
    namespace Koa {
        ...

        export interface Request {
            ...
        }
        ...
    }
    ...
    namespace Koa {}
    export = Koa;
}

I'm using the bodyparser middleware so Request has a property named body but typescript is unaware of this and so I'm trying to add that by adding this definition file as a reference:

/// <reference path="globals/koa/index.d.ts" />
/// <reference path="koa.d.ts" />

import koa = require("koa");
...
app.use(ctx => {
    console.log(ctx.request.body); // error: Property 'body' does not exist on type 'Request'
});

Where koa.d.ts is:

declare module "koa" {
    namespace Koa {
        export interface Request {
            body: any;
        }
    }

    export default Koa;
}

But this is probably the wrong way to do it as it's not working.
How can it be done?
Thanks.

2

2 Answers

1
votes

I just had to work through this. I added this to my custom-typings.d.ts:

import {Request} from "koa";

declare module "koa" {
  interface Request {
    body: any;
  }
}
1
votes

Just ran into this. I found that since I was using koa-bodyparser middleware, I needed to install the @types/koa-bodyparser module which augments the interface for you - https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/koa-bodyparser/index.d.ts#L20.

import * as bodyparser from 'koa-bodyparser'; 
...    
app.use(bodyParser());

Then, in your route, "body" will be available on the request object.

ctx.request.body