gpt4 book ai didi

typescript - 减少 TypeScript 导出中的冗余

转载 作者:行者123 更新时间:2023-12-04 16:03:38 24 4
gpt4 key购买 nike

models 中的每个 TypeScript 文件目录导出一个主要类型和与其相关的方法集合。

export type User = { ... }

export function addToTeam() { ... }

我正在通过 index.ts 重新导出所有这些文件在目录的根目录。
import * as User from "./User";
import * as Team from "./Team";

export { User, Team };

当引用代码库其余部分的主要类型时,这会增加一些冗余。
import { User, Team } from "./models";

function join(user: User.User, team: Team.Team) {
return User.addToTeam(user.id, team.id);
}

由于类型和值不在同一范围内,因此可以以相同的名称导出两者。
// models/index.ts
import * as _User from "./User";
import * as _Team from "./Team";

export const User = _User;
export type User = _User.User;

export const Team = _Team;
export type Team = _Team.Team;

这意味着导入的标识符可以引用两者。
import { User, Team } from "./models";

function join(user: User, team: Team) {
return Foo.createFoo(foo);
}

有没有办法在不创建新类型和新变量的情况下以相同的名称导出两者?

以下是一些不成功的尝试示例。
// TypeScript doesn't support "export * as"
export * as User from "./User";
export { User } from "./User";

// Duplicate exports
import * as User from "./User";
export type User = User.User;
export { User };

// Duplicate exports
import * as User from "./User";
import { User as UserType } from "./User";
export { User, UserType as User }

// Duplicate exports
import * as User from "./User";
export { User } from "./User";
export { User };

以上所有的主要问题是 export { ... } form 似乎在类型和值范围内都可以导出。

以下是我不感兴趣的其他一些解决方法:
  • 将函数包装在与类型
  • 同名的命名空间中
  • 更改
  • 类型的导出名称
  • 使用带有静态方法的类型化类
  • 最佳答案

    在 index.ts 中,您应该能够从模块中导出...无需先导入它。

    import * as User from "./User";
    import * as Team from "./Team";

    export { User, Team };

    改成:
    export * from "./User";
    export * from "./Team";

    然后您将能够删除这些多余的名称:
    import { User, Team } from "./models";

    function join(user: User, team: Team) {
    return addToTeam(user.id, team.id);
    }

    关于typescript - 减少 TypeScript 导出中的冗余,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57886431/

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