I’m using this library https://github.com/chentsulin/koa-bearer-token which adds an extra property to the koa libraries request object like ctx.request.token
. So if I use the koa types directly I get an error which tells me the token
property doesn’t exist on ctx.request.token
.
My current solution
I created a type definition file called koa-bearer-token.d.ts
which contains types for the library and exports for the extended koa context/request type:
declare module 'koa-bearer-token' {
import {Context, Request, Middleware} from 'koa';
interface Options {
queryKey?: string;
bodyKey?: string;
headerKey?: string;
reqKey?: string;
}
interface RequestWithToken extends Request {
token?: string
}
interface ContextWithToken extends Context {
request: RequestWithToken
}
export default function bearerToken(options?: Options): Middleware;
export {RequestWithToken, ContextWithToken};
}
Then I use this in other files like:
import {ContextWithToken} from 'koa-bearer-token';
const someFunction = (ctx: ContextWithToken) => {
const token = ctx.request.token; // <-- No longer errors
};
Why I'm asking this question
This works now but I’m concerned it isn’t the best way because it wouldn’t work if I need to add more properties in the future, ideally I want to just create a koa.d.ts
file that adds to the libraries types then I can carry on using import {Context} from 'koa';
instead of import {ContextWithToken} from 'koa-bearer-token';
but when I create koa.d.ts
it overwrites all the library types instead of adding on top of them.
Here is my tsconfig.json in case it helps
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"noImplicitAny": true,
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"baseUrl": ".",
"paths": {
"*": [
"node_modules/*",
"src/@types/*"
]
}
},
"include": [
"src/**/*"
]
}
koa.d.ts
file? It seems odd that I can't do that, say even if I wanted to add types to DefinitelyTyped for koa-bearer-token would there be no way available to sub-library authors to add properties. So everytime anyone installs a sub-library like koa-bearer-token the properties the sub-library adds would always be incorrectly typed? – Calices