tenuej tenuej - 2 months ago 39
Javascript Question

Flow type: use extended class from function returning parent class

How can I get flow to interpret the return value from

document.getElementById
as
HTMLInputElement
, not the more general
HTMLElement
?

Example:

let input = document.getElementById('myinput');
console.log(input.value);


script.js:28
28: console.log(input.value);
^^^^^ property `value`. Property not found in
28: console.log(input.value);
^^^^^ HTMLElement


From https://github.com/facebook/flow/blob/master/lib/dom.js

declare class Document extends Node {

getElementById(elementId: string): HTMLElement;

}


However,
getElementById
may return a subclass (in this case
HTMLInputElement
)

declare class HTMLInputElement extends HTMLElement {

value: string;

}


I'd like to be able to access the
value
property of the input element without flow raising an error.

Answer

The problem is that Flow compiler doesn't know what type of HTMLElement input variable is going to be in advance, it throws error.

Typically this is what people are suggested to do in such cases:

var input = document.getElementById('myinput');

if (input instanceof HTMLInputElement) {
    console.log(input.value);
}

Read about this technic in dynamic type tests section of documentation.