javascript - Typescript utökar tredjeparts deklarationsfiler
Hur kan jag utöka tredjepartsdeklarationsfiler?
till exempel, jag vill utöka Context från @types/koa och lägga till ett extra fält (resource) till det.
Jag försökte detta:
// global.d.ts
declare namespace koa {
interface Context {
resource: any;
}
}
Men det fungerar inte:
error TS2339: Property 'resource' does not exist on type 'Context'.
Uppdatera
en förenklad version av min kod som ger detta fel:
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"
]
}
Svar #1
Du måste använda modulförstärkning som beskrivs här:
import { Context } from "koa";
declare module "koa" {
interface Context {
resource: any;
}
}
