【问题标题】:Extend the window.top through ts type, improve vscode tips通过ts类型扩展window.top,改进vscode提示
【发布时间】:2022-10-24 12:04:03
【问题描述】:

旧项目使用iframe 开发。顶层窗口有很多私有属性,其他页面通过top进行通信。现在想通过 ts 来扩展 iframe 页面中的 top 类型。如何更改以下代码以避免错误

interface TopWindow extends Window {
    createMP: (key?: string) => CustomPlayer;
}

declare var top: TopWindow | null;

上面的代码会导致 ts(2403) 错误

【问题讨论】:

    标签: typescript


    【解决方案1】:

    因为interface merging,你实际上可以使用这个:

    interface Window {
        createMP: (key?: string) => CustomPlayer;
    }
    
    top!.createMP // ok
    

    Window 接口的后续定义合并到“原始”中。

    Playground

    【讨论】:

      猜你喜欢
      • 2012-12-24
      • 1970-01-01
      • 1970-01-01
      • 2021-03-28
      • 2021-08-03
      • 2022-01-25
      • 1970-01-01
      • 2022-11-04
      • 1970-01-01
      相关资源
      最近更新 更多