J. Hesters
J. Hesters

Reputation: 14816

How to tell the compiler about window.Cypress in .tsx files?

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 this answer (amongst others) in Google but I couldn't see how that would solve this specific issue.

EDIT:

The question Tobias linked in a comment is different because if you do:

declare global {
  Cypress: Cypress;
}

TypeScript complains that:

Unexpected labeled statement.

And when you do:

declare global {
  var Cypress: Cypress;
}

TypeScript complains that:

Cannot augment module 'Cypress' with value exports because it resolves to a non-module entity.

I couldn't find the code on Github, but in my node_modules it lives here:

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

Upvotes: 5

Views: 2267

Answers (3)

J. Hesters
J. Hesters

Reputation: 14816

After some playing around the following seems to work:

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

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

Upvotes: 5

tenshi
tenshi

Reputation: 26354

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.

Upvotes: 1

Fody
Fody

Reputation: 32080

The pattern used by Gleb Bahmutov in his slides is

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

if (window.Cypress) {   
  ...
}

Upvotes: 1

Related Questions