【问题标题】:ES2015 module syntax is preferred over custom TypeScript modules and namespaces @typescript-eslint/no-namespace #2ES2015 模块语法优于自定义 TypeScript 模块和命名空间 @typescript-eslint/no-namespace #2
【发布时间】:2022-10-04 21:06:47
【问题描述】:

多年来我一直使用以下代码

export interface User {
  readonly name: User.Name;
  readonly address: User.Address;
}

export namespace User {
  export interface Name {
    readonly first: string;
    readonly last: string;
  }

  export interface Address {
    readonly country: string;
    readonly city: string;
  }
}

我喜欢通过User 接口访问的NameAddress 接口,这有助于防止名称冲突、显示关系等。

现在,我和 ESLint 规则斗争了@typescript-eslint/no-namespace

是否可以在不违反规则的情况下实现相同的打字?

【问题讨论】:

    标签: typescript eslint typing typescript-eslint


    【解决方案1】:

    没有办法使用命名空间在不违反 lint 规则的情况下。

    但是,您可以通过内联类型完全取消命名空间:

    export interface User {
      readonly name: {
        readonly first: string;
        readonly last: string;
      };
      readonly address: {
        readonly country: string;
        readonly city: string;
      };
    }
    

    如果您想稍后在代码中专门引用地址或名称类型,则可以使用索引类型引用来执行此操作:

    type UserName = User['name'];
    type UserAddress = User['address'];
    

    ts playground

    【讨论】:

      猜你喜欢
      • 2020-02-04
      • 2021-01-10
      • 1970-01-01
      • 2016-07-17
      • 2019-04-30
      • 2016-02-25
      • 2016-08-22
      • 1970-01-01
      • 2021-02-06
      相关资源
      最近更新 更多