Is it possible to forcibly cast a variable in Flow?
type StringOrNumber = string | number
const foo: StringOrNumb
This answer is just a suggestion. When browsing around solutions to Event and HTMLElement related type checking issues I encountered a lot of guards invoking instanceof.
To satisfy type checks I just introduced this generic guard and called it cast (which does not of course make it a cast), because otherwise my code got so bloated.
The cost is of course in performance (pretty relevant when writing games, but I guess most use cases benefit more from type guards than milliseconds per iteration).
const cast = (type : any, target : any) => {
if (!(target instanceof type)) {
throw new Error(`${target} is not a ${type}`);
}
return target;
}
Usages:
const fooLayer = cast(HTMLCanvasElement, document.getElementById("foo-layer"));
window.addEventListener("click", (ev : Event) =>
console.log(cast(MouseEvent, ev).clientX - cast(HTMLElement, ev.target).offsetLeft,
cast(MouseEvent, ev).clientY - cast(HTMLElement, ev.target).offsetTop));