gpt4 book ai didi

typescript - 从另一个 TypeScript 包导入 TypeScript 类型

转载 作者:行者123 更新时间:2023-12-04 14:29:29 31 4
gpt4 key购买 nike

我已经写了并且 npm 发布了这个:https://github.com/justin-calleja/pkg-dependents

现在我正在用 Typescript 编写这个包:https://github.com/justin-calleja/update-dependents

我想在 update-dependents 中重新使用 pkg-dependents (IndexInfoDict) 中定义的类型,我想检查是否有比这更好的方法:

在 pkg-dependents 的 index.ts 中:

import { IndexInfoDict } from './interfaces';

export interface IndexInfoDict extends IndexInfoDict {};

即我正在导入 IndexInfoDict 接口(interface)来注释 pkg-dependents 的 index.ts 中的一个函数,但是因为我想在 update-dependents 中使用相同的类型,我不得不导出另一个扩展自身的 IndexInfoDict…

这似乎是一个奇怪的模式,但编译器现在很高兴。


注意:为共享类型采取的额外步骤:

  1. 在 tsconfig.json 中使用 "declaration": true 以便为每个导出内容的 .ts 文件生成一个 .d.ts 文件。
  2. 在 pkg-dependents 的 package.json 中使用“typings”: (path-to-generated-index.d.ts) 这样你就可以在你的其他 Typescript 项目中导入 index.js 并且它会通过索引知道索引文件的 API .d.ts.
  3. 要实际导入类型并重新使用它:import { IndexInfoDict } from 'pkg-dependents/lib/index.d.ts';

有人可以确认没有更好的方法吗?

我想要但不知道是否可行的是:

  1. 不必以扩展自身的方式导出 IndexInfoDict(我可以只导出类型……这很有意义)。
  2. 以某种方式避免在导入中使用“pkg-dependents/lib/index.d.ts”。它可以只是 import { pkgDependents, IndexInfoDict } from 'pkg-dependents' ... 但是因为 'pkg-dependents' 指的是一个 JS 文件(pkg-dependents 的 package.json 的主要是 ./lib/index.js),我怀疑这是否可行。

编辑 1:

我越想越觉得上面的 2(避免'pkg-dependents/lib/index.d.ts')似乎是不可能的。我希望 tsc 有一些魔力来弄清楚从 'index.d.ts' 获取类型定义,即使正在导入 'index.js' - 这样我就可以 import { pkgDependents, IndexInfoDict } from 'pkg-dependents' 来自 Typescript 项目,只是 import { pkgDependents } from 'pkg-dependents' 来自 JS 项目(没有 tsc magic 并且 JS 没有类型所以 IndexInfoDict出来了)。

目前,我必须:

import pkgDependents from 'pkg-dependents';
import { IndexInfoDict } from 'pkg-dependents/lib';

好吧……也许没有魔法。 1呢?除了导出扩展自身的类型之外,是否有更容易混淆的导出导入类型的方法?

(我在 pkg-dependents 中不止一个地方使用了 IndexInfoDic。其中之一恰好是 index.ts,主要的导出函数。因此,我希望它在 index.ts 之外,但从 index 导出。 ts 所以它在 index.d.ts 中生成,用户从 index.d.ts 中获取主函数使用的类型。

最佳答案

在您的 index.ts 中,您可以:

export { IndexInfoDict } from "./interfaces;

这将从主文件中导出界面。

关于typescript - 从另一个 TypeScript 包导入 TypeScript 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37921852/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com