18

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?

3
  • So, do you think the docs are wrong? What happened when you tried removing the namespace? Commented Apr 25, 2022 at 9:30
  • I think the docs don't take this rule into account because it isn't part of TypeScript. If I removed the namespace Cypress line, I expect it would declare a new Chainable interface unrelated to Cypress.Chainable and so I couldn't call the method on a Cypress.Chainable value; or do you mean something else? (I can't try it right now, but can later if you think it's useful.) Commented Apr 25, 2022 at 10:00
  • 2
    Are you trying with allowDeclarations = true, by default it's false. Also in a different way instead of putting this in global context , did you try creating a separate d.ts file with declare module <> like syntax and then using directly in a .ts file: ///<reference path="../typings/custom/your.d.ts" /> Commented Apr 25, 2022 at 10:55

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this really helped - If needed, adding export {} to the bottom of cypress.d.ts helped (the project I worked on has the namespace declaration inside a global declaration). Hope that helps someone else!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.