如何在 typescript-eslint/no-namespace 下声明 Cypress 自定义命令的类型?

Ale*_*nov 17 typescript cypress typescript-eslint

Cypress 文档显示了如何声明自定义命令类型

declare global {
  namespace Cypress {
    interface Chainable {
      /**
       * Custom command to select DOM element by data-cy attribute.
       * @example cy.dataCy('greeting')
       */
      dataCy(value: string): Chainable<Element>
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但 Typescript ESLint 对此并不满意,因为“ES2015 模块语法优于自定义 TypeScript 模块和命名空间 @typescript-eslint/no-namespace”。是否可以将其重写为导入/导出,如果可以,如何重写?或者我应该禁用这种情况的规则?

Haf*_*ari 9

据此@typescript-eslint/no-namespace规则允许declare在定义文件内使用自定义 TypeScript 命名空间。

因此,您可以创建一个cypress.d.ts定义文件并将自定义命令/断言的类型从支持文件剪切到此文件中:

// ./cypress.d.ts

declare namespace Cypress {
  interface Chainable {
    /**
     * Custom command to select DOM element by data-cy attribute.
     * @example cy.dataCy('greeting')
     */
    dataCy(value: string): Chainable<Element>
  }
}
Run Code Online (Sandbox Code Playgroud)

您可能需要在项目*.d.ts中任何文件的包含选项中包含tsconfig.json,以便 TypeScript 获取新类型:

// ./cypress.d.ts

declare namespace Cypress {
  interface Chainable {
    /**
     * Custom command to select DOM element by data-cy attribute.
     * @example cy.dataCy('greeting')
     */
    dataCy(value: string): Chainable<Element>
  }
}
Run Code Online (Sandbox Code Playgroud)

检查以获取更多信息。