Typescript扩展第三方声明文件 [英] Typescript extend third-party declaration files

查看:330
本文介绍了Typescript扩展第三方声明文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
    }
}

但这不起作用:

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;
    }
}

打字稿v2.4

typescript v2.4

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

推荐答案

您必须使用模块扩充,如下所述:

import { Context } from "koa";

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

这篇关于Typescript扩展第三方声明文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆