我正在使用这个库 https://github.com/chentsulin/koa-bearer-token它向 koa 库请求对象添加了一个额外的属性,如 ctx.request.token
。因此,如果我直接使用 koa 类型,我会收到一个错误,告诉我 ctx.request.token
上不存在 token
属性。
我目前的解决方案
我创建了一个名为 koa-bearer-token.d.ts
的类型定义文件,其中包含库的类型和扩展的 koa 上下文/请求类型的导出:
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};
}
然后我在其他文件中使用它,例如:
import {ContextWithToken} from 'koa-bearer-token';
const someFunction = (ctx: ContextWithToken) => {
const token = ctx.request.token; // <-- No longer errors
};
为什么我要问这个问题
这现在有效,但我担心这不是最好的方法,因为如果我将来需要添加更多属性,它就不会起作用,理想情况下我只想创建一个 koa.d.ts
添加到库类型的文件,然后我可以继续使用 import {Context} from 'koa';
而不是 import {ContextWithToken} from 'koa-bearer-token' ;
但当我创建 koa.d.ts
时,它会覆盖所有库类型,而不是在它们之上添加。
这是我的 tsconfig.json 以防有帮助
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"noImplicitAny": true,
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"baseUrl": ".",
"paths": {
"*": [
"node_modules/*",
"src/@types/*"
]
}
},
"include": [
"src/**/*"
]
}
最佳答案
您可以尝试使用模块扩充。您不必声明新模块。 Typescript 将合并这两个模块,您应该拥有旧的 koa 类型和您的新类型。
import * as koa from "koa"
declare module 'koa'{
interface Request {
token: string;
}
}
declare const c: koa.Request;
c.token = 'tre';
棘手的是,它必须放在 koa 导入之后。所以,我建议在一个单独的文件中设置这个新的更改,这样就可以很容易地在任何地方应用您的更改。
import * as koa from "koa";
import '<path to>koachanges';
希望对你有帮助
你说的,我说是有可能的。
更改您的 tsconfig 以添加全局 d.ts 文件。
...
"typeRoots": ["./node_modules/@types", "./typings"]
...
在项目根目录下的这个新的 typings 文件夹中添加一个 index.d.ts 文件并放入其中。
import * as Koa from 'koa';
declare module 'koa'{
interface Request {
token: string;
}
}
添加第一个导入很重要,因为然后将 koa 类型导入到您的全局文件中,然后您可以覆盖它们。
关于typescript - 使用新的定义文件添加到现有库 typescript 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51297601/