Typescript扩展第三方声明文件
Typescript扩展第三方声明文件
如何扩展第三方声明文件?
例如,我想要扩展@types/koa中的Context
,并添加一个额外的字段(resource
)。
我尝试了这个:
// global.d.ts declare namespace koa { interface Context { resource: any; } }
但它不起作用:
error TS2339: 类型 'Context' 上不存在属性 'resource'。
更新
产生此错误的代码的简化版本:
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
// tsconfig.json { "compilerOptions": { "target": "es6", "module": "commonjs", "moduleResolution": "node", "noImplicitAny": true, "experimentalDecorators": true, "emitDecoratorMetadata": true }, "exclude": [ "node_modules" ] }