'How to add types to Cypress.env?

I have this cypress.json config file:

{
  "env": {
    "example": "Hello World!"
  }
}

In my tests:

Cypress.env("example")

Can I add any kind of type defintion to the env system? (to work with Typescript or eslint) I would love to use intellisense here.



Solution 1:[1]

From cypress.d.ts

interface Cypress {
  /**
   * Returns specific environment variable or undefined
   * @see https://on.cypress.io/env
   * @example
   *    // cypress.json
   *    { "env": { "foo": "bar" } }
   *    Cypress.env("foo") // => bar
  */
  env(key: string): any
}

so you can extend it with

declare namespace Cypress {
  interface Cypress {
    env(key: "example"): string
  }
}

which gives intellisense (method) Cypress.Cypress.env(key: "example"): string (+6 overloads)

Solution 2:[2]

According to documentation:

    Cypress.env("myOwnTypeKey", {
        value: "yourOwnKey",
        type: "myOwnTypeClass"
    });

should set a specific variable with myOwnTypeKey. Then you could check if the "yourOwnKey" with a call to instanceof "myOwnTypeClass".

Value could be a complex object as well.

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 Fody
Solution 2