Typescript 扩展第三方声明文件

Typescript extend third-party declaration files

如何扩展第三方声明文件?
例如,我想从 @types/koa 扩展 Context 并向其添加一个额外的字段 (resource)。
我试过这个:

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

但是不行:

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

更新

我的代码的简化版本产生了这个错误:

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"
  ]
}

你必须使用 module augmentation as described here:

import { Context } from "koa";

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