Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript extend third-party declaration files

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"
  ]
}
like image 818
Saman Mohamadi Avatar asked Sep 29 '17 16:09

Saman Mohamadi


People also ask

What is D TS in TypeScript?

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.

What is declare module in TypeScript?

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


1 Answers

You have to use module augmentation as described here:

import { Context } from "koa";

declare module "koa" {
    interface Context {
        resource: any;
    }
}
like image 85
Saravana Avatar answered Sep 24 '22 12:09

Saravana