Home > Software engineering >  How to tell the compiler about window.Cypress in .tsx files?
How to tell the compiler about window.Cypress in .tsx files?

Time:05-07

I'm building an app with Cypress and TypeScript.

I have the following code, which slightly alters the behaviour of the Magic SDK based on whether it runs inside of an E2E tests, or not:

const magic = new Magic(window.ENV.MAGIC_PUBLISHABLE_KEY, {
  testMode: Boolean(window.Cypress),
});

TypeScript complains about window.Cypress and says:

Property 'Cypress' does not exist on type 'Window & typeof globalThis'.

How can I tell TypeScript about Cypress? Basically I need something like this:

type Window = {
  Cypress?: Cypress; // Where Cypress is the Cypress namespace
}

I found enter image description here

So the solutions from the suggested answer won't work, because Cypress is a namespace, and not a type - though to solve this question you probably need it to be a type.

EDIT 2:

Fody's answer doesn't work, either.

enter image description here

CodePudding user response:

After some playing around the following seems to work:

declare global {
  interface Window {
    Cypress?: Cypress.Cypress;
  }
}

if (window.Cypress) {
  // ...
}

CodePudding user response:

The pattern used by Gleb Bahmutov in his slides is

interface Window {
  Cypress? : any    // don't really need strict type here
}

if (window.Cypress) {   
  ...
}

CodePudding user response:

Assign the namespace to a declared constant and export it:

declare global {
  export declare const Cypress: Cypress;
}

Not 100% sure if this works, things with ambient type declarations are always a bit finnicky.

  • Related