【问题标题】:Typescript extend third-party declaration filesTypescript 扩展第三方声明文件
【发布时间】:2018-03-11 14:53:18
【问题描述】:

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

打字稿 v2.4

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

【问题讨论】:

  • 请发布verifiable 示例。请注意,“它不起作用”被明确列为对问题的不充分描述。
  • 删除declare。命名空间已经被第三方库声明了,你只是在扩展它。你必须在你的命名空间中说export interface <interfaceName>Docs Here
  • @jcalz 错误详情已添加
  • @mhodges A 'declare' modifier is required for a top level declaration in a .d.ts file.
  • 如果@Saravana 的回答不能解决您的问题,请附上产生错误的代码。

标签: javascript typescript koa


【解决方案1】:

你必须使用module augmentation as described here:

import { Context } from "koa";

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

【讨论】:

  • 您是否尝试将此添加到单独的*.d.ts 文件中?
  • 是的,它目前位于 global.d.ts 中,但我用另一个单独的文件进行了测试,没有任何改变。
  • 我尝试使用与您使用的完全相同的代码,它对我有用。你能发布一些可以复制的东西吗?
  • 如何在没有“导入”的情况下执行此操作,以便环境文件保持环境状态并且不会模块启动并停止工作?
猜你喜欢
  • 2016-09-27
  • 2018-06-21
  • 2023-04-01
  • 2021-11-13
  • 1970-01-01
  • 2019-03-01
  • 2021-12-06
  • 1970-01-01
  • 2017-09-21
相关资源
最近更新 更多