Typescript extend third-party declaration files
Asked Answered
B

1

33

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"
  ]
}
Bewley answered 29/9, 2017 at 16:33 Comment(6)
Please post a verifiable example. Note that "it doesn't work" is explicitly listed as an insufficient description of a problem.Jawbone
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 <interfaceName> inside your namespace. Docs HereHymnal
@Jawbone Error details has been addedBewley
@Hymnal A 'declare' modifier is required for a top level declaration in a .d.ts file.Bewley
@Hymnal adding export doesn't make any change.Bewley
If @Saravana's answer doesn't fix your problem, please include the code that's producing the error.Jawbone
G
57

You have to use module augmentation as described here:

import { Context } from "koa";

declare module "koa" {
    interface Context {
        resource: any;
    }
}
Ghastly answered 29/9, 2017 at 17:41 Comment(5)
Did you try adding this to a separate *.d.ts file?Ghastly
Yes, It's currently located in global.d.ts, but I have tested with another separate file and nothing changed.Bewley
I tried with the exact same code you are using and it works for me. Can you post something that can be reproduced.Ghastly
How do you do this without the "import" so an ambient file remains ambient and doesn't module-up and stop working?Jesselton
I expanded the FastifyInstance with this trick. Many thanksVenom

© 2022 - 2024 — McMap. All rights reserved.