Augmenting existing interfaces
Asked Answered
C

2

1

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.

Cleres answered 7/8, 2016 at 18:7 Comment(0)
L
1

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;
  }
}
Lynn answered 25/8, 2016 at 17:57 Comment(1)
The question is how can I place that in a single file that I can then use so that I won't need to do this in every file in which I use koa requests?Cleres
B
1

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
Basipetal answered 13/3, 2018 at 17:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.