Typescript 扩展第三方声明文件

Sam*_*adi 15 javascript typescript koa

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

// global.d.ts
declare namespace koa {
    interface Context {
        resource: any;
    }
}
Run Code Online (Sandbox Code Playgroud)

但它不起作用:

error TS2339: Property 'resource' does not exist on type 'Context'.
Run Code Online (Sandbox Code Playgroud)

更新

产生此错误的代码的简化版本:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

打字稿 v2.4

// tsconfig.json
{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "noImplicitAny": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  },
  "exclude": [
    "node_modules"
  ]
}
Run Code Online (Sandbox Code Playgroud)

Sar*_*ana 29

您必须使用此处描述的模块扩充

import { Context } from "koa";

declare module "koa" {
    interface Context {
        resource: any;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 在没有“导入”的情况下如何做到这一点,以便环境文件保持环境状态并且不会模块启动并停止工作? (5认同)