2016-10-14 28 views
3

流量似乎並沒有認識到querySelector可以返回HTMLElement亞型:流量HTMLElement.querySelector返回一個iframe

var myIframe = document.querySelector('iframe'); 

function foo(iframe: HTMLIFrameElement): void { 
    // I want to do iframe stuff! 
} 

foo(myIframe); 

主要生產

10: foo(myIframe); 
     ^HTMLElement. This type is incompatible with 
6: function foo(iframe: HTMLIFrameElement): void { 
         ^HTMLIFrameElement 

https://flowtype.org/try

有沒有什麼辦法可以鍵入myIframe,讓我打字它作爲Object同時使用其HTMLElement特性及其HTMLIFrameElement性質,分開?

回答

7

Flow不知道如何解析一個選擇器,它需要做些什麼來理解返回哪種元素。它能夠理解getElementsByTagName的更簡單的API,所以it knowsgetElementsByTagName('iframe')返回HTMLCollection<HTMLIFrameElement>

使用querySelector,您需要施放它。事情是這樣的:

var myIframe = ((document.querySelector('iframe'): any): HTMLIFrameElement);

+0

感謝的是,固定我的問題,並指出我的鑄造文檔:https://flow.org/en/docs/types/casting/ – Ben

+0

感謝。我理解你是否必須投射「任何」,因爲它可能會返回一組元素? – mepler