'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:
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.
Solution 1:[1]
After some playing around the following seems to work:
declare global {
interface Window {
Cypress?: Cypress.Cypress;
}
}
if (window.Cypress) {
// ...
}
Solution 2:[2]
The pattern used by Gleb Bahmutov in his slides is
interface Window {
Cypress? : any // don't really need strict type here
}
if (window.Cypress) {
...
}
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | J. Hesters |
| Solution 2 | Fody |
| Solution 3 | hittingonme |


