[英]Typescript extend third-party declaration files
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. 例如,我想从@ types / koa扩展Context
并为其添加一个额外的字段( resource
)。
I tried this: 我试过这个:
// global.d.ts
declare namespace koa {
interface Context {
resource: any;
}
}
But it doesn't work: 但它不起作用:
error TS2339: Property 'resource' does not exist on type 'Context'.
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;
}
}
typescript v2.4 打字稿v2.4
// tsconfig.json
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"moduleResolution": "node",
"noImplicitAny": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true
},
"exclude": [
"node_modules"
]
}
You have to use module augmentation as described here : 您必须使用此处所述的模块扩充 :
import { Context } from "koa";
declare module "koa" {
interface Context {
resource: any;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.