方法/属性不存在

时间:2016-04-17 02:21:57

标签: iframe typescript

我正在尝试转换JavaScript代码

if (window.ifEdit.editIsDirty()) { }

进入Typescript。我得到了以下

var iframe = document.getElementById('ifEdit');
var iWindow = <HTMLIFrameElement>(iframe).contentWindow;

var _editIsDirty = iWindow.editIsDirty();

我在'contentWindow'和'editIsDirty'下得到红色曲线,说该类型上不存在方法/属性。 .ts不会编译为.js文件。

我已经搜索过,但找不到解决方案。

2 个答案:

答案 0 :(得分:11)

对于contentWindow部分,代码的问题在于转换是错误的,应该是:

var iWindow = (<HTMLIFrameElement> iframe).contentWindow;

对于editIsDirty,它不是Window的标准属性 如果它是在您运行javascript的环境中添加的内容,那么您需要声明它如下:

interface IfEdit {
    editIsDirty(): boolean;
}

interface Window {
    ifEdit: IfEdit;
}

var iframe = document.getElementById("ifEdit");
var iWindow = (<HTMLIFrameElement> iframe).contentWindow;

var _editIsDirty = iWindow.ifEdit.editIsDirty();

使用Playground中的代码。

答案 1 :(得分:0)

铸造将通过 as。这确保 .contentWindow 是可访问的。

const iframe = document.getElementById('embed-player') as HTMLIFrameElement;

if (!iframe) {
  // Handle case where iframe not found
  return;
}

const contentWindow = iframe.contentWindow;

// Note: You will likely need more null handling for contentWindow's properties
console.log(contentWindow?.document);
相关问题