在编译输出中包含外部类型定义

Include external type definitions in compilation output

我正在用 TypeScript 编写一个库:@cjol/core。它有一个 JavaScript 依赖项 dep,它没有可用的 @types 包。相反,我编写了一个自定义的 dep.d.ts 文件,这使得在我开发库时所有的输入都能很好地工作。一切都编译得很好 但是 我的 dep.d.ts 没有出现在输出的任何地方。

当我尝试将我的库包含在另一个客户端项目中时 @cjol/client,客户端项目将无法编译。我收到这样的错误:

../core/build/index.d.ts:2:24 - error TS7016: Could not find a declaration file for module 'dep'. '/home/cjol/.../dep/index.js' implicitly has an 'any' type.
  Try `npm install @types/dep` if it exists or add a new declaration (.d.ts) file containing `declare module 'dep';`

2 > import { Foo } from "dep";

我也在使用 Yarn 工作区(@cjol/core@cjol/client 都是同一个工作区中的包,在 ./core./client 下),但我没有认为这在这里是相关的。我需要 @cjol/client 来输出我的自定义定义文件,但我不知道如何实现它!


编辑 1: 同样,我不确定细节是否相关,但 index.d.ts 看起来像这样。如前所述,它是由 TypeScript 生成的。

import { Stuff } from "a-typescript-library";
import { Foo } from "dep";

export * from "./my-app-types";

declare type APIResponse<T> = {
    /* ... */
};
export declare class API {
    /* ... */
}

编辑 2: 这是 dep.d.ts 的样子:

declare module "dep" {
  import Something from "something.js";
  export class DepClass {
     /* loads of stuff */
  }
}

编辑 4: 也许是另一种思考我的问题的方式。如果我编写了自定义 .d.ts 文件,我该如何分发它?我是否需要创建一个包含类型定义的全新包?

好的,我想我知道这里发生了什么,因为我以前遇到过。我敢打赌您没有在项目的 baseUrl 定义位置创建 dep.d.ts。 TypeScript 会自动选取在基根中声明的任何模块,其他任何内容都需要映射到 tsconfig.json 中。这个 属性 叫做 path - 路径映射。

https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping

示例 tsconfig.json 如果您使用正确的映射信息将路径 属性 添加到此配置文件,应该可以解决您的问题。

{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "dep": ["src/typings/dep"] // That location is a example but you need to point that at where your dep.d.ts file is
    }
  }
}

不幸的是,typescript 不会将您的自定义 *.d.ts 文件复制到您的输出中。但是,有几种方法可以解决这个问题。

首先,是在完成 运行 tsc 后手动将自定义 *.d.ts 文件复制到输出目录中,并确保目录结构与 src目录。

另一种选择是将 dep.d.ts 文件重命名为 dep.ts 文件,并将其包含在需要该类型的模块中。

文件现在名为 dep.ts

declare module "dep" {
  import Something from "something.js";
  export class DepClass {
     /* loads of stuff */
  }
}

dep.ts导入到需要它的模块中。

import './types/dep';
import { Foo } from 'dep';

// Rest of your code here