首页 > 解决方案 > 使用新定义文件添加到现有库 typescript 类型

问题描述

我正在使用这个库https://github.com/chentsulin/koa-bearer-token它为 koa 库请求对象添加了一个额外的属性,例如ctx.request.token. 因此,如果我直接使用 koa 类型,我会收到一个错误,告诉我该token属性不存在于ctx.request.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/**/*"
  ]
}

标签: typescripttypeskoa

解决方案


您可以尝试使用模块扩充。您不必声明新模块。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 类型导入全局文件,然后您可以覆盖它们。


推荐阅读