gpt4 book ai didi

typescript - 从 typescript 模块导出所有类型(并且只是类型)

转载 作者:行者123 更新时间:2023-12-03 14:52:51 73 4
gpt4 key购买 nike

如果我想导出一个模块的所有导出成员(包括代码),我可以使用

export * from 'module'
如果我想在没有代码的情况下导出类的类型,我可以这样做
export type {typeName} from 'module'
现在我需要从模块中导出所有类型,无需代码。我很想这样做
export type * from 'module'
因为这是直观的东西,但 typescript 类型 exports must be named exports (TS 1383)。
那么我怎样才能从模块中导出所有内容,使其成员不能在运行时使用呢?
我能想到的解决方法:
  • 克服它并使用export * .这是一个选项。但是对于我们的用例,我不希望我们库的用户使用这些类,只使用它们来注释它们的类型
  • 问漂亮-请所有使用我们图书馆的人请使用import type {typeName} from 'myLibrary' .我想这也是一种选择,但我如何说服用户这样做呢?

  • tl;dr:如何在 Typescript 中模拟全局类型导出?

    最佳答案

    如您的 referenced pull request 中所述, 类型的通配符重新导出尚未实现(并且可能永远不会实现)。因此,目前不可能将所有类型重新导出到根级别。您可以获得的最接近的方法是将重新导出的类型包装在它们自己的命名集合中:

    // your-module
    import type * as Types from "external-module";
    export { Types };

    // Usage by the end user
    import { Types } from "your-module";
    let a:Types.Class;
    这种方法的缺点是用户无法独立导入类型,如 import { Class } from "your-module";。 .但是,这些类型仅作为类型导出,因此这仍然不会影响您的包的大小,并且仍然无法实例化导出的类型。

    关于typescript - 从 typescript 模块导出所有类型(并且只是类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63588268/

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