Flow: How to define custom method of HTMLElement?

Created on 11 Jan 2016  路  3Comments  路  Source: facebook/flow

I have a plugin object(ActiveX/NPAPI) and it has a custom method foo which is not defined in prototype of HTMLElement. If I get this object by document.getElementById then invoke this custom method, errors will occur for flow type checking.

Is there any way to extend definitions of HTMLElement?

HTML:

<object id="my_plugin"> ... </object>

JavaScript:

document.getElementById('my_plugin').foo();

Flow check:

>> main.js:317,20,64: property foo
>> Property not found in
>>   [LIB] dom.js:361,1,1: HTMLElement

Most helpful comment

You can define a new type using class:

declare class CustomHTMLElement extends HTMLElement {
  foo(): void;
}

Or using an intersection:

type CustomHTMLElement = HTMLElement & {
  foo(): void;
}

And then use down cast from any:

el: CustomHTMLElement = (document.getElementById("my_plugin"): any)
el.foo()

All 3 comments

You can define a new type using class:

declare class CustomHTMLElement extends HTMLElement {
  foo(): void;
}

Or using an intersection:

type CustomHTMLElement = HTMLElement & {
  foo(): void;
}

And then use down cast from any:

el: CustomHTMLElement = (document.getElementById("my_plugin"): any)
el.foo()

In my case, we didn't write type annotations in source code, cause build system doesn't support Babel to transform away Flow syntax yet. And we use flow interface files to help type checking.

Regrading the down case suggestion of document.getElementById(), it seems no chance to do it within interface file, writing type annotation along with source code turns to a MUST-BE solution.

Fortunately, Flow supports special comments to allow writing type annotations without strip them out before running JavaScript.

Here is my implementation.

Flow interface file:

declare class CustomHTMLElement extends HTMLElement {
  foo(): void;
}

JavaScript:

/* @Flow */
el/* : CustomHTMLElement */ = (document.getElementById("my_plugin")/* : any */)
el.foo()

Defining custom type with special comments works!
Thanks all :+1:

Was this page helpful?
0 / 5 - 0 ratings