如何扩展“窗口"打字稿界面 [英] How to extend the 'Window' typescript interface

查看:102
本文介绍了如何扩展“窗口"打字稿界面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的示例中,我试图扩展TS Window接口以包括fetch的polyfill.为什么没关系.问题是" 如何告诉TS window.fetch是有效函数? "

In my example, I'm trying to extend the TS Window interface to include a polyfill for fetch. Why doesn't matter. The question is "how do I tell TS that window.fetch is a valid function?"

我正在使用运行TS v.1.5(IIRC)的VS Code v.0.3.0进行此操作.

I'm doing this in VS Code, v.0.3.0 which is running TS v.1.5 (IIRC).

在我要使用的TS类文件中声明接口不起作用:

Declaring the interface inside my TS class file where I want to use it doesn't work:

///<reference path="typings/tsd.d.ts"/>

interface Window {
  fetch:(url: string, options?: {}) => Promise<any>
}
...
window.fetch('/blah').then(...); // TS objects that window doesn't have fetch

但是如果我在一个单独的".d.ts"文件中声明相同的接口并在我的TS类文件中引用它,也可以.

But it's OK if I declare this same interface in a separate ".d.ts" file and reference it in my TS class file.

这是"typings/window.extend.d.ts"

Here is "typings/window.extend.d.ts"

///<reference path="es6-promise/es6-promise"/>
interface Window {
  fetch:(url: string, options?: {}) => Promise<any>
}

现在我可以在我的TS类文件中使用它了:

Now I can use it in my TS class file:

///<reference path="typings/window.extend.d.ts"/>
...
window.fetch('/blah').then(...); // OK

或者,我可以在我的TS类文件中写一个扩展接口用另一个名称,然后在强制转换中使用它:

Alternatively, I can write an extending interface with another name in my TS class file and then use it in a cast:

interface WindowX extends Window {
  fetch:(url: string, options?: {}) => Promise<any>
}
...
(<WindowX> window).fetch('/blah').then(...); // OK

为什么扩展接口可以在"d.ts"中工作,而不能在原位 中工作?

Why does extending the interface work in a "d.ts" but not in situ?

我真的必须经历这些回转吗?

推荐答案

您需要declare global

declare global {
  interface Window {
    fetch:(url: string, options?: {}) => Promise<any>
  }
}

然后可以正常工作

window.fetch('/blah').then(...); 

这篇关于如何扩展“窗口"打字稿界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆