Alexey Romanov
Alexey Romanov

Reputation: 170825

How to declare types for Cypress custom commands under typescript-eslint/no-namespace?

Cypress documentation shows how to declare custom command types:

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>
    }
  }
}

But Typescript ESLint is unhappy about this due to "ES2015 module syntax is preferred over custom TypeScript modules and namespaces @typescript-eslint/no-namespace". Is it possible to rewrite this to import/export and if so, how? Or should I just disable the rule for this case?

Upvotes: 17

Views: 6510

Answers (1)

Hafez Divandari
Hafez Divandari

Reputation: 9059

According to this, @typescript-eslint/no-namespace rule allows declare with custom TypeScript namespaces inside definition files.

So you may create a cypress.d.ts definition file and cut the types for your custom commands/assertions from the support file into this file:

// ./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>
  }
}

You might need to include the *.d.ts in the include options in any tsconfig.json files in your project for TypeScript to pick up the new types:

// tsconfig.json

"include": [
  "src",
  "./cypress.d.ts"
]

check this for more info.

Upvotes: 10

Related Questions