Typescript扩展了第三方声明文件

时间:2017-09-29 16:33:12

标签: javascript typescript koa

如何扩展第三方声明文件?
例如,我想从@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"
  ]
}

1 个答案:

答案 0 :(得分:3)

您必须使用module augmentation as described here

import { Context } from "koa";

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