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.
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
// tsconfig.json
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"moduleResolution": "node",
"noImplicitAny": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true
},
"exclude": [
"node_modules"
]
}
The "d. ts" file is used to provide typescript type information about an API that's written in JavaScript. The idea is that you're using something like jQuery or underscore, an existing javascript library. You want to consume those from your typescript code.
The TypeScript declares module is one of the modules and keyword it is used for to surround and define the classes, interfaces; variables are also declared it will not originate with the TypeScript like that module is the set of files that contains values, classes, functions/methods, keywords, enum all these contains ...
You have to use module augmentation as described here:
import { Context } from "koa";
declare module "koa" {
interface Context {
resource: any;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With