Adding to existing library typescript types with a new definition file

An alternate more extensible solution to adding the types to koa-bearer-token.d.ts would be to add a file like koa-extensions.d.ts and add any extra properties there like so:

import {Context, Request} from 'koa';

declare namespace KoaExtensions {
    interface KoaRequest extends Request {
        token?: string
    }

    interface KoaContext extends Context {
        request: KoaRequest
    }
}

export = KoaExtensions;

Then the extended types can be imported:

import {KoaContext} from './@types/koa-extensions';
const someFunction = (ctx: KoaContext) => {
    const token = ctx.request.token; // <-- No longer errors
};

This is an improvement on my initial solution but it still seems like I should be able to globally augment the Koa module types in a local koa.d.ts file.


You can try with module augmentation. You don't have to declare a new module. Typescript is going to merge both modules and you should have the legacy koa typings plus your new ones.

import * as koa from "koa"
declare module 'koa'{
    interface Request {
        token: string;
    }
}

declare const c: koa.Request;
c.token = 'tre';

The tricky thing is that it has to be placed just after the koa import. So, I would suggest to set this new change in a separated file so it is easy to apply your change everywhere.

import * as koa from "koa";
import '<path to>koachanges';

Hope that helps

Regarding you have said, I would say it is possible.

Change your tsconfig in order to add a global d.ts file.

 ...
 "typeRoots": ["./node_modules/@types", "./typings"]
 ...

Add an index.d.ts file in this new typings folder in the root directory of your project and place in it.

import * as Koa from 'koa';
declare module 'koa'{
    interface Request {
        token: string;
    }
}

It is important to add the first import as then is importing the koa typings to your global file and then you can override them.