30

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'.

Update

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"
  ]
}
Community
  • 1
  • 1
Saman Mohamadi
  • 4,454
  • 4
  • 38
  • 58
  • Please post a [verifiable](https://stackoverflow.com/help/mcve) example. Note that "it doesn't work" is explicitly listed as an insufficient description of a problem. – jcalz Sep 29 '17 at 16:37
  • Remove `declare`. The namespace has already been declared by the third party library, you are just extending it. And you have to say `export interface ` inside your namespace. [`Docs Here`](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#merging-namespaces) – mhodges Sep 29 '17 at 16:38
  • @jcalz Error details has been added – Saman Mohamadi Sep 29 '17 at 16:41
  • @mhodges `A 'declare' modifier is required for a top level declaration in a .d.ts file.` – Saman Mohamadi Sep 29 '17 at 16:44
  • @mhodges adding export doesn't make any change. – Saman Mohamadi Sep 29 '17 at 16:46
  • 3
    If @Saravana's answer doesn't fix your problem, please include the code that's producing the error. – jcalz Sep 29 '17 at 17:53

1 Answers1

54

You have to use module augmentation as described here:

import { Context } from "koa";

declare module "koa" {
    interface Context {
        resource: any;
    }
}
Saravana
  • 37,852
  • 18
  • 100
  • 108