簡體   English   中英

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

打字稿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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM