Search code examples
javascripttypescriptkoa

Typescript extend third-party declaration files


How can I extend third-party declaration files?
for example, I want to extend Context from @types/koa and add an extra field(resource) to it.
I tried this:

// global.d.ts
declare namespace koa {
    interface Context {
        resource: any;
    }
}

But it doesn't work:

error TS2339: Property 'resource' does not exist on type 'Context'.

Update

a simplified version of my code which produces this error:

import {Context} from 'koa';
import User from './Models/User';
class Controller {
   async list(ctx: Context) {
        ctx.resources = await User.findAndCountAll();
        ctx.body = ctx.resources.rows;
        ctx.set('X-Total-Count', ctx.resources.count.toString());
        ctx.status = 200;
    }
}

typescript v2.4

// tsconfig.json
{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "noImplicitAny": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  },
  "exclude": [
    "node_modules"
  ]
}

Solution

  • You have to use module augmentation as described here:

    import { Context } from "koa";
    
    declare module "koa" {
        interface Context {
            resource: any;
        }
    }