flow icon indicating copy to clipboard operation
flow copied to clipboard

How to define custom method of HTMLElement?

Open mjj2000 opened this issue 10 years ago • 3 comments

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

mjj2000 avatar Jan 11 '16 03:01 mjj2000

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()

ooflorent avatar Jan 15 '16 07:01 ooflorent

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()

yeddaliu avatar Jan 18 '16 16:01 yeddaliu

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

mjj2000 avatar Jan 19 '16 02:01 mjj2000