How can Flow be forced to cast a value to another type?

后端 未结 4 1562
执笔经年
执笔经年 2021-01-01 09:53

Is it possible to forcibly cast a variable in Flow?

type StringOrNumber = string | number
const foo: StringOrNumb         


        
4条回答
  •  醉梦人生
    2021-01-01 10:04

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

提交回复
热议问题