代码之家  ›  专栏  ›  技术社区  ›  J. Hesters

如何告诉编译器有关窗口的信息。tsx文件中的Cypress?

  •  0
  • J. Hesters  · 技术社区  · 4 年前

    我正在用Cypress和TypeScript构建一个应用程序。

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

    TypeScript抱怨 window.Cypress 并说:

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

    我怎样才能告诉TypeScript Cypress

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

    我找到了 this answer (除其他外)但我不知道这将如何解决这个具体问题。

    托拜厄斯在评论中链接的问题是不同的,因为如果你这样做:

    declare global {
      Cypress: Cypress;
    }
    

    Unexpected labeled statement.
    

    declare global {
      var Cypress: Cypress;
    }
    

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

    我在Github上找不到代码,但在我的 node_modules 它住在这里:

    enter image description here

    编辑2:

    enter image description here

    0 回复  |  直到 4 年前
        1
  •  1
  •   J. Hesters    4 年前

    在进行了一些变通之后,以下内容似乎奏效了:

    declare global {
      interface Window {
        Cypress?: Cypress.Cypress;
      }
    }
    
    if (window.Cypress) {
      // ...
    }
    
        2
  •  0
  •   Fody    4 年前

    Gleb Bahmutov在幻灯片中使用的模式是

    interface Window {
      Cypress? : any    // don't really need strict type here
    }
    
    if (window.Cypress) {   
      ...
    }
    
        3
  •  0
  •   mochaccino    4 年前

    将命名空间分配给声明的常量并将其导出:

    declare global {
      export declare const Cypress: Cypress;
    }